SQL - 有效地比较两个表中的所有列数据



我有两个表,比如Table1和Table2,它们具有相同的列和相同的模式结构。

现在我想从表2中的表1中选择数据。但是,在比较数据时,我希望比较这两个表中的所有列。类似地,表1中的整个记录应该出现在表2中。在SQL Server 2008中,实现这一目标的最快、最高效的方法是什么?这两个表都包含大约1000-2000条记录,并且这些表将非常频繁地被访问。

intersect运算符正是这样做的:

SELECT *
FROM   table1
INTERSECT
SELECT *
FROM   table2

有了"exists",就有了一个解决方案:

select * from Table1 t1 where 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 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 ...
   ) 

最新更新