如何检查不同表中两列的内容是否相同?

How to check if the contents of two columns from different tables are identical?

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

OK case,因为两个 table 在 Specifier 列中具有相同顺序的相同数据:

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

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

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

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

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

错误案例,因为数据的顺序不同:

-- 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       

我写了下面的查询,它几乎可以工作,如果一个 table 有一个值而另一个没有,它会正确地给出一个错误,但是如果只有订单是不正确:

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;

似乎

可能更容易
IF EXISTS (SELECT 1
           FROM (SELECT ROW_NUMBER() OVER (ORDER BY RowID) AS RN,
                        Specifier
                 FROM Table1) T1
                FULL OUTER JOIN (SELECT ROW_NUMBER() OVER (ORDER BY RowID) AS RN,
                                        Specifier
                                 FROM Table2) T2 ON T1.RN = T2.RN
                                                AND T1.Specifier = T2.Specifier
           HAVING COUNT(CASE WHEN T1.RN IS NULL OR T2.RN IS NULL THEN 1 END) >= 1) ...

您可以使用 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 的第一个查询应该会更快。