首页 > 解决方案 > 如何检查来自不同表的两列的内容是否相同?

问题描述

我的 SQL 数据库中有两个表。我想检查Specifier列是否以完全相同的顺序具有完全相同的数据。

好的 case,因为两个表在列中以相同的顺序具有相同的数据Specifier

-- Table1:
RowID   Specifier
187     1         
188     1         
189     2         

-- Table2:
RowID   Specifier
181     1         
182     1         
183     2       

ERROR case,因为数据不同:

-- Table1:
RowID   Specifier
187     1         
188     2         
189     3         

-- Table2:
RowID   Specifier
181     1         
182     2         
183     2    

ERROR case,因为数据的顺序不同:

-- Table1:
RowID   Specifier
187     1         
188     1         
189     2         

-- Table2:
RowID   Specifier
181     1         
182     2         
183     1   

错误案例,因为数据量不同:

-- Table1:
RowID   Specifier
187     1         
188     1         
189     2         

-- Table2:
RowID   Specifier
181     1         
182     1         
183     2
184     1       

我编写了以下查询,它几乎可以正常工作,并且如果一个表具有另一个表没有的值,则会正确给出错误,但如果只有顺序不正确,它将不正确地给出错误:

IF EXISTS
    (SELECT Specifier FROM Table1 EXCEPT SELECT Specifier FROM Table2
    UNION ALL
    SELECT Specifier FROM Table2 EXCEPT SELECT Specifier FROM Table1)
BEGIN
    THROW 99999, 'Mismatching Specifiers between the two tables', 1;
END;

标签: sqlsql-servertsqlsql-server-2016

解决方案


您可以使用full joinrow_number()。以下获取异常:

select *
from (select t1.*, row_number() over (order by rowid) as seqnum
      from table1 t1
     ) t1 full join
     (select t2.*, row_number() over (order by rowid) as seqnum
      from table2 t2
     ) t2
     on t1.seqnum = t2.seqnum and t1.specifier = t2.specifier
where t1.seqnum is null or t2.seqnum is null;

如果您只是想要一个标志:

select (case when count(*) > 1 then 1 else 0 end)
from (select t1.*, row_number() over (order by rowid) as seqnum
      from table1 t1
     ) t1 full join
     (select t2.*, row_number() over (order by rowid) as seqnum
      from table2 t2
     ) t2
     on t1.seqnum = t2.seqnum and t1.specifier = t2.specifier
where t1.seqnum is null or t2.seqnum is null;

如果您关心性能,则使用第一个查询exists应该更快。


推荐阅读