[英]Compare Two SQL identical Table to find missing records
我正在使用SQL2008。我有两个具有相同列名的相同表。
在表2上,我缺少一些记录。 表2中删除了一些记录。
我必须比较表1和表2,并仅从表1中检索丢失的记录。
使用LEFT JOIN
并检查IS NULL
如下所示。 仅当table1中存在表2中不存在的记录时, where t2.col2 is null
TRUE
。 您在寻找什么。 [这是示例代码,与您的原始查询不相似]
select t1.col1,t1.col2,t1.col3
from table1 t1
left join table2 t2 on t1.some_column = t2.some_column
where t2.col2 is null
您应该使用SQL Except。 没有参与。
Select * from dbo.TableA
Except
Select * from dbo.TableB
在集合论中,集合A,B(AB)的差是属于A而不属于B的元素集合。
使用“不存在”,您有一个解决方案:
select * from Table1 t1 where not exists (select 1 from Table2 t2
where t1.col1 = t2.col1
and t1.col2 = t2.col2
and t1.col3 = t2.col3
and ... // check here all columns ...
)
但是,在null值的情况下,此解决方案存在一个小问题,只能通过“ IS NOT NULL”或“ IS NULL”进行测试,因此是补充解决方案:
select * from Table1 t1 where not exists (select 1 from Table2 t2
where (t1.col1 = t2.col1 or (t1.col1 IS NULL and t2.col1 IS NULL))
and (t1.col2 = t2.col2 or (t1.col2 IS NULL and t2.col2 IS NULL))
and (t1.col3 = t2.col3 or (t1.col3 IS NULL and t2.col3 IS NULL))
and ... // check here all columns ...
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.