Monday, 3 September 2018

PHP - How to make a complete outer join of two tables with the same layout that does not repeat?

I have to tables with the same layout (same columns). There is one ID and other data. I need a query that returns only one ID setting the data fields to null if that ID wasn't available at the required table.

Example:
Table A
ID - Val1 - Val2
1 - 2 - 2
2 - 3 - 3
4 - 1 - 5

Table B
ID - Val1 - Val2
2 - 3 - 3
3 - 2 - 1
4 - 2 - 3

Result
ID - Val1A - Val2A - Val1B - Val2B
1 - 2 - 2 - NULL - NULL
2 - 3 - 3 - 3 - 3
3 - NULL - NULL - 2 - 1
4 - 1 - 5 - 2 - 3

I'm using MS SQL Server. Thanks!

use coalesce to grab the non null id, the other columns will be null for the non matching table
select coalesce(a.id,b.id) as ID, Val1A , Val2A , Val1B , Val2B
from TableA a
Full outer join tableB b
ON <.....>

0 comments:

Post a Comment