sql - 如何检查来自不同表的两列的内容是否相同?
问题描述
我的 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;
解决方案
您可以使用full join
和row_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
应该更快。
推荐阅读
- c++ - 自 C++17 的类模板参数推导以来,std::make_move_iterator 是多余的吗?
- python-3.x - Xlsxwriter 在图表上显示不同类型的数据
- ms-access - ms-Access 清除基于 True/False 控件的文本框
- javascript - 检测没有散列或后退/前进弹出状态的 URL 更改
- firebase - Firebase Firestore 数据库上的 Dart/Flutter 验证/验证
- ruby-on-rails - Ruby-on-Rails:具有任意数量组件的路径路径?
- linux - npm install 不关心 package-lock.json
- bash - Azure CLI az functionapp config appsettings - appsetting 中的空格
- python-2.7 - 如何获取最新的 Google Chrome 浏览器版本来更新我的用户代理?
- android - 无法访问androidx.lifecycle.LifecycleOwner,Android中error是什么意思?