[英]Select single row with multiple rows in joined table
我有一个联系表,如下所示:
contactid | contactname
----------|-------------
C1 | Name1
C2 | Name2
我有一个沟通表如下
contactid | communication_type | communication_string
----------|--------------------|---------------------
C1 | Phone | 9090909090
C1 | Email | c1@email.com
C2 | Phone | 9191919191
C2 | Email | c1@email.com
现在,我的要求是查询这两个表,以便结果如下:
contactid | contactname | phonenumber | emailaddress
----------|-------------|---------------|----------------
C1 | Name1 | 9090909090 | c1@email.com
C2 | Name2 | 9191919191 | c2@email.com
如果我定期加入,
SELECT cont.contactid, cont.contactname,
comm.communication_type, comm.communication_string
FROM contact cont
LEFT JOIN communication comm ON cont.contactid = comm.contactid
我会得到类似
contactid | contactname | communication_type| communication_string
----------|-------------|-------------------|----------------
C1 | Name1 | Phone | 9090909090
C1 | Name1 | Email | c1@email.com
C2 | Name2 | Phone | 9191919191
C2 | Name2 | Email | c2@email.com
但这不是我想要的。 我希望两个通信字符串都在结果的同一行中,而不是在不同的行中。
完全有可能得到这样的结果吗?
另一个要求是该解决方案应该是通用的,才能在所有数据库上工作。
您可以使用条件聚合:
select cont.contactid,
cont.contactname,
max(case when comm.communication_type = 'Phone' then comm.communication_string end) PhoneNumber,
max(case when comm.communication_type = 'Email' then comm.communication_string end) EmailAddress
from contact cont
left join communication comm on cont.contactid = comm.contactid
group by cont.contactid,
cont.contactname;
对于给定的contactId,这将返回一个电话号码和电子邮件地址。
该解决方案将在大多数RDBMS中运行。
您可以在不同条件下多次连接同一张表:
select c.contactid
,c.contactname
,cp.comunication_string as 'phonenumber'
,ce.comunication_string as 'emailaddress'
from contact c
left join
communication cp on c.contactid = cp.contactid
and cp.comunication_type = 'Phone'
left join
communication ce on c.contactid = ce.contactid
and ce.comunication_type = 'Email'
标准SQL,易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.