查询以比较具有相同结构的两个表?

时间:2019-11-26 16:03:25

标签: sql sql-server

我想比较两个具有相同精确结构(相同列名称)的表。

DROP TABLE IF EXISTS my_before;
DROP TABLE IF EXISTS my_after;

CREATE TABLE my_before
(
     pk INT NOT NULL IDENTITY(1, 1) PRIMARY KEY, 
     myvalue INT NULL
);

CREATE TABLE my_after
(
     pk INT NOT NULL IDENTITY(1, 1) PRIMARY KEY, 
     myvalue INT NULL
);

INSERT INTO my_before (myvalue) VALUES (10), (NULL), (12), (NULL);
INSERT INTO my_after (myvalue) VALUES (10), (11), (NULL), (NULL), (NULL), (14);

我想输出my_before和my_after之间的差异。

enter image description here

查询是什么样的?

3 个答案:

答案 0 :(得分:3)

您可以使用full join来执行此操作,但是(处理NULL值)的正确逻辑是:

SELECT a.*, b.*
FROM my_before a FULL OUTER JOIN
     my_after b
     ON a.pk = b.pk
WHERE a.pk IS NULL OR
      b.pk IS NULL OR
      a.my_value <> b.my_value OR
      (a.my_value IS NULL AND b.my_value IS NOT NULL) OR
      (a.my_value IS NOT NULL AND b.my_value IS NULL);

答案 1 :(得分:1)

SELECT a.*, b.*
FROM my_before AS a
FULL OUTER JOIN my_after AS b ON a.pk=b.pk
WHERE a.pk IS NULL OR b.pk IS NULL
 OR COALESCE(a.myvalue,0) != COALESCE(b.myvalue,0)

enter image description here

没有COALESCE,结果将完全不同(并且是错误的)

SELECT a.*, b.*
    FROM my_before AS a
    FULL OUTER JOIN my_after AS b ON a.pk=b.pk
    WHERE a.pk IS NULL OR b.pk IS NULL
     OR a.myvalue != b.myvalue

enter image description here

答案 2 :(得分:0)

“之后”表中缺少记录:

select * from my_before
except
select * from my_after

“之前”表中缺少记录:

select * from my_after
except
select * from my_before