SQL - 加入,但包含null结果(好像没有连接)?

时间:2013-01-30 19:20:05

标签: sql sql-server-2008 join

我有一个Contacts表和一个Businesses表,它们通过Contacts_vs_Businesses表连接(这是多对多关系)。

我想查询两个表;如果联系人与两个企业有关,我想退货:

  • 包含所有联系方式和商业A的所有详细信息的行;
  • 包含所有联系方式和Business B
  • 所有详细信息的行
  • 包含所有联系人详细信息并且根本没有商业详细信息的行(就好像我刚在第一张桌子上完成了基本SELECT

联系人表

ID Contact_Name Contact_Phone
1  Jez Clark    01234 567 890
2  Someone Else 01254 648 654

企业表

ID Business_Name   Business_Address
1  A Company       24, A Street, A Town
2  Another Company 43, Another Street, Another Town

Contacts_vs_Businesses

Contact_ID Business_ID
1          1
1          2
2          2

我想回来:

Contact_Name Contact_Phone Business_Name   Business_Address
Jez Clark    01234 567 890 A Company       24, A Street, A Town
Jez Clark    01234 567 890 Another Company 43, Another Street, Another Town
Jez Clark    01234 567 890 NULL            NULL

我在使用SQL Server 2008 R2。

我怎么会这样做(我猜它真的很容易......)?我已经尝试了OUTER和INNER以及LEFT / RIGHT联接的各种排列,但似乎没有人给我最后一行结果。

由于

2 个答案:

答案 0 :(得分:3)

如果我正确理解您的问题,对于与2个企业相关联的任何联系人,您希望显示与每个企业的联系,然后是NULL业务,从而产生3条记录?

使用GROUP BY尝试使用UNION获取计数并使用SELECT C.Contact_Name, C.Contact_Phone, B.Business_Name, B.BusinessAddress FROM Contacts C INNER JOIN Contacts_vs_Businesses CB ON C.Id = CB.Contact_ID INNER JOIN Businesses B ON CB.Business_Id = B.Id INNER JOIN (SELECT Contact_ID, COUNT(*) cnt FROM Contacts_vs_Businesses GROUP BY Contact_ID) CB2 ON C.Contact_ID = CB2.Contact_Id WHERE CB2.cnt = 2 UNION SELECT C.Contact_Name, C.Contact_Phone, NULL, NULL FROM Contacts INNER JOIN Contacts_vs_Businesses CB ON C.Contact_ID = CB.Contact_Id GROUP BY C.Contact_Name, C.Contact_Phone HAVING Count(*) = 2 返回NULL记录:

{{1}}
祝你好运。

答案 1 :(得分:0)

这不是一个简单的查询,因为它需要连接和联合。前两项非常标准。引入第三个是需要union all的地方:

select Contact_Name, Contact_Phone, Business_Name, Business_Address
from Contacts_vs_Businesses cb join
     Businesses b
     on cb.Business_Id = b.id join
     Contacts c
     on cb.Contact_Id = c.id
union all
select Contact_Name, Contact_Phone, NULL, NULL
from Contacts
where Contact_Id in (select Contact_id
                     from Contacts_vs_Businesses cb
                     group by Contact_id
                     having COUNT(*) = 2
                    )