为什么这个NOT IN查询按预期工作,但不是这个NOT EXISTS查询?

时间:2013-12-12 00:14:55

标签: sql sql-server-2008 exists not-exists

工作(NOT IN)检索3行:

select DISTINCT d.* from Device d , Company c3
WHERE d.deviceid NOT IN
(
    Select d1.deviceid from Device d1, Clone x1 
    WHERE  d1.deviceid =  x1.deviceID 
    AND  
    (
        x1.XPath = 'hi' 
        OR x1.XPath = 'bye' 
    )
    AND 
    ( 
        EXISTS ( select * from (SELECT * FROM [dbo].[Split] ('T130SF0W2050', ',')) as s 
        WHERE x1.Value like '%' + s.items + '%' )
    ) 
)  
AND  
d.companyid = c3.companyid and c3.companynumber in (SELECT * FROM [dbo].[Split] ('00223200', ','))

不工作(不存在):

select DISTINCT d.* from Device d , Company c3
WHERE  NOT EXISTS
(Select * from Device d1, Clone x1 
    WHERE  d1.deviceid =  x1.deviceID 
    AND  
    (
        x1.XPath = 'hi' 
        OR x1.XPath = 'bye' 
    )
    AND 
    ( 
        EXISTS ( select * from (SELECT * FROM [dbo].[Split] ('T130SF0W2050', ',')) as s 
        WHERE x1.Value like '%' + s.items + '%' )
    )

)  
AND  
d.companyid = c3.companyid and c3.companynumber in (SELECT * FROM [dbo].[Split] ('00223200', ','))

我不确定我是否使用了存在的语法,我应该从子查询中选择什么?我尝试过几种不同的组合。如果我放WHERE d.deviceid NOT EXISTS

,它将无法运行

解决方案(感谢Nikola):

在Exists子查询中添加AND d1.deviceid = d.deviceid

1 个答案:

答案 0 :(得分:1)

不同之处在于NOT IN查询返回与公司匹配且与内部查询规范不匹配的设备。

要使NOT EXIST查询按写入方式工作(其中“work as written”指的是返回与top查询相同的结果),则不能存在与内部查询匹配的任何设备。如果任何设备与内部查询完全匹配,则查询不会返回任何结果。