比较两个SQL相同的表以查找丢失的记录

时间:2014-06-17 20:43:13

标签: sql sql-server sql-server-2008

我正在研究SQL 2008.我有两个相同的表,具有相同的列名。

在Table2上,我错过了一些记录。一些记录在表2中被删除。

我必须比较Table1和Table2,并从table1中仅检索丢失的记录。

3 个答案:

答案 0 :(得分:6)

使用LEFT JOIN并检查IS NULL,如下所示。仅当table1中有记录不存在于table2中时,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

答案 1 :(得分:1)

您应该使用SQL Except。没有加入。

Select * from dbo.TableA
Except
Select * from dbo.TableB

在集合论中,集A,B(A-B)的差异是属于A且不属于B的元素集。

答案 2 :(得分:0)

用"不存在",你有一个解决方案:

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

在空值的情况下,此解决方案存在一些问题,只能通过" 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 ...
   ) 
相关问题