2015-08-09 27 views
1

我有两个表:为什么哪里都不存在表达不给正确的输出

表:#A

ID |名称
10 | a
20 | b
30 | c
40 | d
50 | Ë

表:#B

ID |名称

10 | a

30 | a

50 |一个

我希望所有的#A表ID中不存在的#B

下面的查询工作:

select * from #a as a 
where not exists(select * from #b as b where a.id = b.id) 

但我无法理解,为什么下面的查询不起作用

select * from #a as a 
where exists(select * from #b as b where a.id <> b.id) 

回答

2

为什么哪里都不存在表达不给正确的输出

第一个查询就能够产生正确的结果:选择从所有记录可是没有合适的匹配B中

但是第二个在逻辑上是不同的。

综观:

;with A(id,name) as 
(
select 10,'a' UNION ALL 
select 20,'b' UNION ALL 
select 30,'c' UNION ALL 
select 40,'d' UNION ALL 
select 50,'e' 

) ,B(id,name) as 
(
select 10,'a' UNION ALL 
select 30,'a' UNION ALL 
select 50,'a' 

) 

select * from a as a 
where exists(select * from b as b where a.id <> b.id) 

对于来自a每个记录,显示是否存在从b记录与非匹配的ID记录。

所以对于10,a(在a有(!)从B记录,其中id10,因此它确实产量10,a(从a)!

现在 - 你看到问题了吗?

+0

明白了...谢谢 – sam

1

这两个查询是不同的,所以结果是不同的。

1)首先查询显示从a所有行其不是(not exists)在ba.id = b.id

2)第二查询显示从a所有行具有在bexists)至少一个不同的行(a.id <> b.id)。

;WITH 
a AS (SELECT * FROM (VALUES (10, 'a'),(20, 'b'),(30, 'c'),(40, 'd'),(50, 'e')) x(id, name)), 
b AS (SELECT * FROM (VALUES (10, 'aa'),(30, 'aaa'),(50, 'aaaa')) x(id, name)) 
SELECT *, 
     CASE WHEN not exists(select * from b where a.id = b.id) THEN 1 ELSE 0 END AS Test1_NOT_EXISTS, 
     CASE WHEN exists(select * from b where a.id <> b.id) THEN 1 ELSE 0 END AS Test2_EXISTS, 
     (select top(1) b.id from b where a.id <> b.id) AS Test2_EXISTS_OneDifferentIDFromB 
FROM a 

输出:

/* 
id   name Test1_NOT_EXISTS Test2_EXISTS Test2_EXISTS_OneDifferentIDFromB 
----------- ---- ---------------- ------------ -------------------------------- 
10   a 0    1   30 
20   b 1    1   10 
30   c 0    1   10 
40   d 1    1   10 
50  
相关问题