Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 join 3 tables with unique values

Author  Topic 

JustinMcDonald
Starting Member

2 Posts

Posted - 2010-08-20 : 00:56:52
Hello,

I have 3 tables:

table_1
key1 value1
a 1
b 2
c 3
d 4

table_2
key2 value2
a 5
b 6
e 7
f 8

table_3
key3 value3
a 9
c 10
e 11
g 12


How do i write a join query to merge all three tables into one table and give me the following result:


key1 val1 key2 val2 key3 val3
a 1 a 5 a 9
b 2 b 6 NULL NULL
c 3 NULL NULL c 10
d 4 NULL NULL NULL NULL
NULL NULL e 7 e 11
NULL NULL f 8 NULL NULL
NULL NULL NULL NULL g 12


Could anyone please help me create a query to join these three tables like this.

Thank you.

Justin

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2010-08-20 : 02:36:10
Try this -


SELECT * FROM table_1
full outer join table_2 on table_1.key1 = table_2.key2
full outer join table_3 on table_2.key2 = table_3.key3 or table_1.key1 = table_3.key3


Vaibhav T

To walk FAST walk ALONE
To walk FAR walk TOGETHER
Go to Top of Page

JustinMcDonald
Starting Member

2 Posts

Posted - 2010-08-20 : 03:04:32
Thank you, that worked perfectly.

Justin
Go to Top of Page

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2010-08-20 : 03:21:06
Welcome

Vaibhav T

To walk FAST walk ALONE
To walk FAR walk TOGETHER
Go to Top of Page
   

- Advertisement -