SQLTeam.com | Weblogs | Forums

Join statement to create table with many cols


#1

Hi everyone,
I'm trying to create a join statement to match data from columns in 3 separate tables and combine in one neat table.

      Col1     Col2     Col3

ID n1
ID n2
ID n3

Col1 is from Table A
Col2 is from Table B
Col3 is from Table C

I want a table with IDs in the first column, and data corresponding to Cols 1, 2 and 3, taken from Tables A, B and C, respectively.

Please can someone help me?


#2
SELECT
	a.ID,
	a.Col1,
	b.Col2,
	c.Col3
FROM
	TableA AS a
	INNER JOIN TableB AS b ON a.ID = b.ID
	INNER JOIN TableC AS c ON a.ID = c.ID;

There is one thing about the query above that may (or may not) be a problem for you. An Id must be present in all three tables for it to be returned in the results. If you have the situation where one or more tables do not have an Id and you still want to get the results, you will need to change the joins to a LEFT/RIGHT/FULL as the case may be.