SQL-返回行之间的差异(在两个不同的表中),但仅在两个表中都存在行ID的情况下

时间:2018-08-16 15:02:37

标签: sql sqlite

我有两个表,其中包含两个可能要引起的差异:仅在其中一个表中存在的行,以及在两个表中存在的行(共享一个公共ID),但其中一个具有不同的值列(两个表中的列完全相同)。

CREATE TABLE "MyTable1" (ID INTEGER, FIRST_NAME TEXT, DOB DATE);
INSERT INTO MyTable1 VALUES (1, "Tom", "01-02-18");
INSERT INTO MyTable1 VALUES (2, "Dick", "02-02-18");
INSERT INTO MyTable1 VALUES (3, "Larry", "03-02-18");
INSERT INTO MyTable1 VALUES (4, "Jebroni", "04-02-18");

CREATE TABLE "MyTable2" (ID INTEGER, FIRST_NAME TEXT, DOB DATE);
INSERT INTO MyTable2 VALUES (1, "Tom", "01-02-18");
INSERT INTO MyTable2 VALUES (2, "Dick", "02-02-18");
INSERT INTO MyTable2 VALUES (3, "Barry", "03-02-18");

我可以返回MyTable2中不存在的MyTable1中的ID:

SELECT MyTable1.*
FROM MyTable1
WHERE MyTable1.ID NOT IN (SELECT MyTable2.ID FROM MyTable2)

返回我想要的东西:

ID      FIRST_NAME      DOB
"4"     "Jebroni"       "04-02-18"

对于第二部分,我想比较共享公用ID的行的每一列的值。

SELECT 'TABLE1' AS SRC, MyTable1.*
FROM (
        SELECT * FROM MyTable1
        EXCEPT
        SELECT * FROM MyTable2
    ) AS MyTable1
UNION ALL
SELECT 'TABLE2' AS SRC, MyTable2.*
FROM (
        SELECT * FROM MyTable2
        EXCEPT
        SELECT * FROM MyTable1
    ) AS MyTable2

返回的内容比我想得到的要多-在一个表中而不是另一个表中存在的行:

SRC         ID      FIRST_NAME  DOB
"TABLE1"    "3"     "Larry"     "03-02-18"
"TABLE1"    "4"     "Jebroni"   "04-02-18"
"TABLE2"    "3"     "Barry"     "03-02-18"

我应该如何调整上一个查询,以使结果改为:

SRC         ID      FIRST_NAME  DOB
"TABLE1"    "3"     "Larry"     "03-02-18"
"TABLE2"    "3"     "Barry"     "03-02-18"

即根据两个表中都存在ID来限制返回什么?

2 个答案:

答案 0 :(得分:1)

将第一组行限制为另一个表中具有匹配ID的行:

SELECT 'TABLE1' AS SRC, *
FROM (
        SELECT * FROM MyTable1 WHERE ID IN (SELECT ID FROM MyTable2)
        EXCEPT                 -------------------------------------
        SELECT * FROM MyTable2
    )
UNION ALL
SELECT 'TABLE2' AS SRC, *
FROM (
        SELECT * FROM MyTable2 WHERE ID IN (SELECT ID FROM MyTable1)
        EXCEPT                 -------------------------------------
        SELECT * FROM MyTable1
    );

答案 1 :(得分:1)

我只会使用join

select *
from MyTable1 t1 join
     MyTable2 t2
     on t1.id = t2.id
where t1.firstname <> t2.firstname or t1.dob <> t2.dob;

我不认为基于集合的操作会完全满足您的要求。但是您可以添加到查询中:

where id in (select id from mytable1 t1
             intersect
             select id from mytable2 t2
            )

这会将结果限制为两个表中的ID,而您不必列出其余的列。