aliassce
aliassce

Reputation: 1197

How to get one of multiple related columns

I have a notes table which stores notes about customers, jobs and products tables.
Customers, jobs and products tables have "Name" and "Id" (GUID) columns.
I want to get a note and its related object name in one query. (If my note is related to a customer, the related object name would be customername, and so on.)

Is it possible to do this with a single query? If so, how?

Upvotes: 0

Views: 84

Answers (1)

Mark Roberts
Mark Roberts

Reputation: 460

select
    notes.id,
    notes.content as content,
    coalesce(customers.name, jobs.name, products.name) as name,
    customers.id as customer_id,
    jobs.id as job_id,
    products.id as product_id
from notes
    left outer join customers on notes.relatedobjid = customers.id
    left outer join jobs      on notes.relatedobjid = jobs.id
    left outer join products  on notes.relatedobjid = products.id
;

Wrap this with some logic in the DAO / display code (python because it's fairly easy to read):

for row in query.list():
    if row["customer_id"] is not None:
        display_type = "customer name"
    elif row["job_id"] is not None:
        display_type = "job name"
    elif row["product_id"] is not None:
        display_type = "product name"
    display_note(display_type, row["name"], row["content"])

The extra columns and display logic may or may not be necessary, depending on how attached you are to the idea of having it say "Customer name". I'd probably keep it, personally. I think you could probably shuffle a lot of this logic off into your Object Relational Mapping if you have one. That may or may not be such a hot idea, depending on how many rows you have in the notes table.

Upvotes: 1

Related Questions