Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR JOIN in SQL

Tags:

sql

join

tsql

I have the following tables

Table A

ID "Other Columns"  
1  
2  
3  

Table B

ID "Other Columns"  
3  
4  
5  

What is the efficient way to return the below result?
Result

ID "Other Columns"  
1  
2  
4  
5
like image 231
Senthil_Arun Avatar asked Mar 11 '23 00:03

Senthil_Arun


2 Answers

You want to use left and right join and union them

Select TableA.ID as 'ID','Other Colums'
FROM TableA Left join TableB
ON TableA.ID=TableB.ID
WHERE TableB.ID IS NULL
UNION
Select TableB.ID as 'ID','Other Colums'
FROM TableA Right join TableB
ON TableA.ID=TableB.ID
WHERE TableA.ID IS NULL
like image 35
Ritesh Patel Avatar answered Mar 13 '23 12:03

Ritesh Patel


A full outer join should work, and only go through each table once. They can be tricky, so test carefully!

SELECT
   isnull(A.ID, B.ID)  ID
  ,"Other columns"  --  Handle nulls properly!
 from TableA  A
  full outer joing TableB  B
   on B.ID = A.ID
 where not (A.ID is not null
            and B.ID is not null)
like image 175
Philip Kelley Avatar answered Mar 13 '23 13:03

Philip Kelley