找出记录集中的差异

时间:2013-11-13 16:27:59

标签: sql sql-server sql-server-2008 full-outer-join

我想知道2个记录集是否不同。我使用了full outer join。简单的例子:

select count(*) from 
(
 select 1 as c
 union 
 select 2 as c 
) t1
full outer join 
(
 select 1 as c 
 union 
 select 3 as c
) t2 on t1.c = t2.c
where t1.c is null or t2.c is null

SQLFiddle

如果记录集相等,则count()返回0

有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

如果记录集中的c是唯一的,您可以使用GROUP BYHAVING执行此操作,如下所示:

SELECT COUNT(*) FROM (
    SELECT c FROM (
        SELECT c FROM record_set_1
    UNION ALL
        SELECT c FROM record_set_2
    ) all_data
    GROUP BY c
    HAVING COUNT(*) <> 2
) non_matched

SQLFiddle

答案 1 :(得分:0)

您可以使用EXISTS

IF EXISTS(SELECT null FROM t1 where c NOT IN (SELECT c FROM t2))
OR EXISTS(SELECT null FROM t2 where c NOT IN (SELECT c FROM t1))

当然,这并没有告诉你哪些记录不匹配 - 如果你想知道你的原始查询就好了。