I have a Contacts table and a Businesses table, they are joined via a Contacts_vs_Businesses table (it’s a many-to-many relationship).
I want to query the two tables; if a contact is related to two businesses, I want to return:
- A row with all contact details and all details of Business A;
- A row with all contact details and all details of Business B
- A row with all contact details and NO business details at all (as if I’d just done a basic
SELECTon the first table)
Contacts Table
ID Contact_Name Contact_Phone
1 Jez Clark 01234 567 890
2 Someone Else 01254 648 654
Businesses Table
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
I want to return:
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
I’m on SQL Server 2008 R2.
How would I go about this (I’m guessing it’s something REALLY easy…)? I’ve tried the various permutations of OUTER and INNER and LEFT/RIGHT joins, but none seem to give me that last line of results.
Thanks
If I’m understanding your question correctly, for any contact that is associated with 2 businesses, you want to show that contact with each business, followed by a NULL business, resulting in 3 records?
Try something like this using
GROUP BYto get counts andUNIONto return the NULL record:Good luck.