简体   繁体   English

在 SQL 中连接 A 列或 B 列上的两个表

[英]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:使用 SQL,我如何识别“在计划中而不是在实际中”的行:

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.您可以使用 LEFT JOIN。 Below is the example with MySql.下面是 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.如果您使用 ORACLE,则可以使用运算符 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;如果您使用的是 SQL Server; use EXCEPT instead of minus.使用 EXCEPT 而不是减号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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