如何获取多个相关列中的一个

时间:2012-06-01 15:43:42

标签: sql

我有一个笔记表,存储有关客户,工作和产品表的说明 客户,作业和产品表具有“名称”和“Id”(GUID)列 我想在一个查询中获取一个注释及其相关的对象名称。 (如果我的笔记与客户有关,则相关对象名称为customername,依此类推。)

是否可以使用单个查询执行此操作?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:1)

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
;

用DAO /显示代码中的一些逻辑包装它(python,因为它相当容易阅读):

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"])

额外的列和显示逻辑可能是必需的,也可能不是必需的,这取决于您对其说“客户名称”的想法。亲自,我可能会保留它。我想如果你有一个逻辑,你可能会把很多这个逻辑拖入你的对象关系映射。这可能是也可能不是一个好主意,具体取决于您在注释表中有多少行。