比较两个具有相同列的表,并报告差异,其中一列作为参考列

时间:2019-07-12 07:14:35

标签: sql ms-access compare

我有两个桌子。表T1具有以下列和行:

#A    B   C   D
-----------------
P1   01  C1  1
P1   02  C2  2
P2   01  C3  1
P2   02  C4  3

表T2的列与T1相同,但数据有所不同

#A   B   C   D
---------------
P1  01  C1  1 
P1  02  C9  8
P1  03  C5  1 
P2  01  C6  2
P2  05  C8  4

A和B列共同构成主键。

我想通过将列A保留为两个表之间的参考列来比较两个表。在我的输出中,我想看看两个表之间的区别。

#A     B    C    D   B    C    D   T1-vs-T2
---------------------------------------------
P1    01   C1   1   01   C1   1    Match
P1    02   C2   2   02   C9   8    No Match
P1    --   --   -   03   C5   1    Not in T1
P2    01   C3   3   01   C6   2    No Match
P2    02   C4   3   --   --   -    Not in T2
P2    --   --   -   05   C8   4    Not in T1

2 个答案:

答案 0 :(得分:2)

您正在寻找完整的外部联接。 Access不直接支持完整的外部联接运算符,但我们可以使用联合查询对其进行仿真。

SELECT
    t1.A AS A,
    t1.B AS B,
    t1.C AS t1_C,
    t1.D AS t1_D,
    t2.C AS t2_C,
    t2.D AS t2_D,
    IIF(t1.C = t2.C AND t1.D = t2.D, 'Match',
        IIF(t1.A IS NOT NULL AND t2.A IS NOT NULL, 'No Match',
        'Not in T2')) AS T1_vs_T2
FROM Table1 t1
LEFT JOIN Table2 t2
    ON t1.A = t2.A AND t1.B = t2.B
UNION ALL
SELECT
    t2.A,
    t2.B,
    t1.C,
    t1.D,
    t2.C,
    t2.D,
    'Not in T1'
FROM Table1 t1
RIGHT JOIN Table2 t2
    ON t1.A = t2.A AND t1.B = t2.B
WHERE
    t1.A IS NULL;

答案 1 :(得分:0)

我认为实现逻辑的更好方法是从 all id开始,然后仅使用left join

select ab.a, ab.b, t1.c, t1.d, t2.c, t2.d,
       switch(t1.a is null, 'Not in t1',
              t1.b is null, 'Not in t2',
              t1.c = t2.c and t1.d = t2.d, 'Match',
              1=1, 'No Match'
             ) as t1_vs_t2
from ((select a, b from t1
       union -- on purpose to remove dups
       select a, b from t2
      ) ab left join
      t1
      on t1.a = ab.a and t1.b = ab.b
     ) left join
     t2
     on t2.a = ab.a and t2.b = ab.b;

我之所以喜欢这样做,是因为比较的逻辑全部放在一个地方。