我有一个注释表,其中存储有关客户、工作和产品表的注释。
客户、工作和产品表具有“名称”和“ID”(GUID) 列。
我想在一个查询中获取注释及其相关对象名称。(如果我的注释与客户相关,则相关对象名称将为customername
,依此类推。)
是否可以通过单个查询来做到这一点?如果是这样,怎么做?
我有一个注释表,其中存储有关客户、工作和产品表的注释。
客户、工作和产品表具有“名称”和“ID”(GUID) 列。
我想在一个查询中获取注释及其相关对象名称。(如果我的注释与客户相关,则相关对象名称将为customername
,依此类推。)
是否可以通过单个查询来做到这一点?如果是这样,怎么做?
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"])
额外的列和显示逻辑可能是必要的,也可能不是必要的,这取决于您对“客户名称”这个想法的依附程度。我个人可能会保留它。如果你有一个,我认为你可能会将很多这种逻辑改组到你的对象关系映射中。这可能是也可能不是一个热门的想法,具体取决于您在笔记表中有多少行。