0

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

我想查询这两个表;如果一个联系人与两个业务相关,我想返回:

  • 一行包含所有联系方式和企业 A 的所有详细信息;
  • 包含所有联系方式和业务 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 连接的各种排列,但似乎没有一个能给我最后一行结果。

谢谢

4

2 回答 2

3

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

尝试使用这样的方法GROUP BY来获取计数并UNION返回 NULL 记录:

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

祝你好运。

于 2013-01-30T19:22:41.810 回答
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
                    )
于 2013-01-30T19:37:21.543 回答