2010-07-15 52 views
7

寻找在SQL Server中设置“差异”的easist /最具扩展性的方式,请参阅下文。 alt textSQL Server差异(与intersect相反)

如果你不能从图片中发现我正在寻找所有不在路口的东西。

我已经看到了这样做的一种方法:

select * from (  
    (select 'test1' as a, 1 as b) 
union all 
    (select 'test2' as a , 2 as b union all select 'test1' as a , 1 as b) 
)un group by a,b having count(1)=1 

但我担心如果我用了两个大集(我不会从选择'恒报表查询会发生什么,我的查询将被拉动从实际表)

编辑:

可能的解决方法......

drop table #temp_a; 
drop table #temp_b; 

go 


    select * into #temp_a from (
    select 1 as num, 'String' as two, 'int'as three, 'purple' as four union all 
    select 2 as num, 'dog' as two, 'int'as three, 'purple' as four union all 
    select 3 as num, 'dog' as two, 'int'as three, 'cat' as four) a 

select * into #temp_b from (
    select 1 as num, 'String' as two, 'decimal'as three, 'purple' as four union all 
    select 2 as num, 'dog' as two, 'int'as three, 'purple' as four union all 
    select 3 as num, 'dog' as two, 'int'as three, 'dog' as four) b 





    SELECT IsNull(a.num, b.num) A,IsNull(a.two, b.two) B, IsNull(a.three, b.three) C,     
     IsNull(a.four, b.four) D 
    FROM #temp_a a 
    FULL OUTER JOIN #temp_b b ON (a.num=b.num AND a.two=b.two and a.three=b.three and a.four=b.four) 
    WHERE (a.num is null or b.num is null ) 

结果:

1字符串INT紫色

3狗INT猫

1字符串十二月紫色

3狗INT狗

回答

15

如何像这样?

SELECT A, B FROM Table1 EXCEPT SELECT A,B FROM Table2 
UNION 
SELECT A, B FROM Table2 EXCEPT SELECT A,B FROM Table1 

这里是完全外部的例子连接方法(假设是不可为空两个表中)

SELECT IsNull(Table1.A, Table2.A) a,IsNull(Table1.B, Table2.B) B 
FROM Table1 
FULL OUTER JOIN Table2 ON (Table1.A=Table2.A AND Table1.B=Table2.B) 
WHERE Table1.A is null or Table2.A is null 
+0

什么是ISNULL部分实现?它只是一种“显示”缺失的手段吗? – Nix 2010-07-16 12:40:37

+1

对于只有一个表中有记录的行(所需的行),在一个表或另一个表中将出现空值。例如,Table1.A将为null或者Table2.A对于每行都将为null。 Isnull从任何一方获得价值的价值。 – JohnFx 2010-07-16 14:01:02

5

什么你之后被称为Full Outer Join, which SQL Server supports

+0

我最初以为这样的事情: SELECT * FROM (选择 '测试1' 为,1为b)一个 FULL JOIN (选择 '测试2' 为,2为B联盟的所有选择 '测试1' 的, 1作为b)两个 \t ON One.a <> Two.a AND One.b <> Two.b 然而,它不是(运行两个SQL) – 2010-07-15 22:02:16

+1

是的,但你也必须过滤掉所有匹配后的加入:'WHERE keyA为NULL或者keyB为NULL' – 2010-07-15 22:10:11

+1

完全外连接不是问题所要求的。完整的外连接将完全填充维恩图,而不仅仅是维恩图的非相交部分。 – Dogs 2017-03-21 13:06:50

9

备选:

SELECT A, B FROM Table1 UNION SELECT A,B FROM Table2 
EXCEPT 
SELECT A, B FROM Table2 INTERSECT SELECT A,B FROM Table1