简体   繁体   中英

Joining two tables on column A or column B in SQL

I have two tables called Plan and Actual. Every row in each table represents a unique item, and I need to find items that are in the Plan table, but not the Actual table, and vice versa.

There are three columns that uniquely identify each item, and the value for each of these columns may or may not be null.

For Example:

Say "Plan" looks like this:

ID_1        ID_2         ID_3
aaa         Null         Null 
Null        111          Null
Null        Null         123
bbb         222          Null 
ccc         Null         456
Null        333          789
ddd         444          202

Say "Actual" looks like this:

ID_1         ID_2            ID_3
aaa          Null            Null
Null         111             Null
bbb          222             Null 
Null         333             789
Null         555             Null 
eee          Null            303

Using SQL, how can I identify the "In plan not in actual" rows of:

Null     Null       123
ccc      Null       456
ddd      444        202

And in "In actual not in plan" rows of:

Null     555   Null 
eee      Null  303

Thank you for your help!

You can use the LEFT JOIN. Below is the example with MySql.

In plan not in actual

SELECT Plan.* FROM Plan 
LEFT JOIN Actual ON (Plan.ID_1 = Actual.ID_1 AND Plan.ID_2 = Actual.ID_2 AND Plan.ID_3 = Actual.ID_3) 
WHERE Actual.ID_1 IS NULL AND Actual.ID_2 IS NULL AND Actual.ID_3 IS NULL;

In actual not in plan

SELECT Actual.* FROM Actual 
LEFT JOIN Plan ON (Plan.ID_1 = Actual.ID_1 AND Plan.ID_2 = Actual.ID_2 AND Plan.ID_3 = Actual.ID_3) 
WHERE Plan.ID_1 IS NULL AND Plan.ID_2 IS NULL AND Plan.ID_3 IS NULL;

If you are using ORACLE, you can use the operator MINUS. It will select rows in table "Plan" not in table "Actual".

SELECT ID_1, ID_2, ID_3
 FROM  Plan
MINUS
SELECT ID_1, ID_2, ID_3
 FROM  Actual;

If you are using SQL Server; use EXCEPT instead of minus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM