Jeremy Jeremy - 15 days ago 7
SQL Question

Join two tables on a third

I can join two tables on a value but, how do you join two tables with different values using a third that contains both values? Such as:

Table A
CustomerID
info
info

Table B
CustomerName
info
info

Table C
CustomerID
CustomerName
info
info


This was my attempt but it failed miserably...

select * from [dbo].[table A] a,
[dbo].[Table B] b
left join [dbo].[Table C] c on c.CustomerID = a.CustomerID
left join [dbo].[Table C] d on d.CustomerName = b.CustomerName


Just a point in the right direction would be very helpful.

Answer
SELECT * 
FROM [dbo].[table A] a
LEFT JOIN [dbo].[Table C] b
 on A.CustomerID = C.Customer_ID
LEFT join [dbo].[Table B] c 
 on c.CustomerName = B.CustomerName

This will include all records from A, those that match in B and those that match from B to C.

So the order of the table and the left join matter.. Do you want all records only where they exist in all 3 tables? all records that exist in A and those that match in B and C? All records that exist in B and only those that match in C and A?

Comments