Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Double-Outer Join?

I have two tables A and B... A and B can be joined by a common column. A and B will have some rows that match on the join column. But A has some rows that B doesn't have, and B has some rows that A doesn't have.

A LEFT OUTER JOIN from A to B will give all rows in A, filling in NULLS for the B columns that couldn't be matched. A RIGHT OUTER JOIN gives all rows in B, filling in NULLS for the A columns that couldn't be matched.

I would like to receive ALL rows from both A and B, while returning NULL for the A columns on rows that are only in B, and NULL for the B columns that are only in A.

I'm know I can do this with UNION along with 1 INNER + 1 LEFT + 1 RIGHT, but is there a single SELECT query that can achieve this?

like image 492
Michael Bray Avatar asked Oct 13 '09 16:10

Michael Bray


2 Answers

You can use a FULL OUTER JOIN for this.

like image 189
Locksfree Avatar answered Oct 18 '22 12:10

Locksfree


You want a full outer join. Don't try doing this with UNIONS -- there are some very tricky edge cases, and it is almost impossible to get right.

Syntax is here:

http://msdn.microsoft.com/en-us/library/aa213228(SQL.80).aspx

like image 36
Ian Clelland Avatar answered Oct 18 '22 13:10

Ian Clelland