为什么不存在表达式不能给出正确的输出

时间:2015-08-09 06:26:31

标签: sql-server-2008

我有两张桌子:

表:#a

id |命名
10 |一个
20 | b
30 | ç
40 | d
50 | ë

表:#b

id |名称

10 |一个

30 |一个

50 |一个

我想要#b

中没有的所有#a表ID

以下查询有效:

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 个答案:

答案 0 :(得分:2)

  

为什么不存在表达式不能提供正确的输出

第一个查询确实产生了正确的结果:选择A中的所有记录,其中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,aa,来自B的{​​{1}}不是id的ARE(!)记录,因此确实 YIELDS 10(来自10,a)!

现在 - 你看到了问题吗?

答案 1 :(得分:1)

这两个查询不同,因此结果不同。

1)第一个查询显示anot exists ba.id = b.id的所有行a

2)第二个查询显示来自exists的所有行,ba.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      

输出:

import json
JSON_FILE = "/tmp/json.json"
with open(JSON_FILE) as infile:
    print infile
    print '\n type of infile is \n', infile
    data = json.load(infile)
    print data
    str_data = json.dumps(data)
    print str_data
相关问题