这是我想要实现的目标: 根据联系类型选择一个人或公司的名称。
表格:
CONTACTS : PEOPLE FIRMS
- id - contact_id - contact_id
- type (person/firm) - name - name
我想要这种魔力:
SELECT type
FROM contacts
WHERE contacts.id = 42;
SELECT model.name
FROM contacts LEFT JOIN model ON model.contact_id = contacts.id
WHERE contacts_id = 42
AND model = CASE (WHEN type = "person" THEN "people"
WHEN type = "firm" THEN "Firms" END); (Not sure this one works)
一站式查询。谢谢 !
答案 0 :(得分:1)
您可以执行以下操作,加入两个表,然后根据contacts.type
决定使用哪个列。
SELECT
(CASE WHEN t1.type = 'person' THEN t2.name WHEN t1.type = 'firm' THEN t3.name) AS contact_name
FROM contacts t1
LEFT JOIN people t2 ON t1.id = t2.contact_id
LEFT JOIN firms t3 ON t1.id = t3.contact_id
答案 1 :(得分:0)
您可以像这样使用动态SQL:
declare
@table_name nvarchar(20),
@query nvarchar(max)
SELECT
@table_name =
case type
when 'person' then 'people'
when 'firm' then 'firms'
end
FROM contacts
WHERE contacts.id = 42;
set @query = N'SELECT ' + @table_name + '.name ' +
'FROM contacts LEFT JOIN model ON ' + @table_name + '.contact_id = contacts.id
WHERE contacts_id = 42 '
exec sp_executesql @query
答案 2 :(得分:0)
简单地离开加入两个表;其中一个将匹配id和类型。然后使用COALESCE显示找到的一个名称。
select coalesce(p.name, f.name) as name
from contacts c
left join people p on p.contacts_id = c.id and c.type = 'person'
left join firms f on f.contacts_id = c.id and c.type = 'firm'
where c.id = 42;
答案 3 :(得分:0)
以下是没有联接的替代方法:
select
case when c.type = 'person' then
(select name from people p where p.contacts_id = c.id)
else
(select name from firms f on f.contacts_id = c.id)
end as name
from contacts c
where c.id = 42;
你知道,有很多方法可以解决这个问题。只需选择您认为最具可读性的那个。