0

在这里找到我的问题的最佳答案:NOT IN 子句和 NULL 值

以下两个查询均不返回任何结果:

select upc 
from   staging..posrecords 
where  upc not in (select upc from mrs..items)

select upc 
from   staging..posrecords 
where  upc in (select upc from mrs..items)

以下两个查询都返回结果:

select upc from staging..posrecords

select upc from mrs..items

鉴于后两个查询都返回结果,我不明白前两个查询怎么可能都不返回任何结果。也许已经晚了,我只是错过了一些非常明显的东西,但我现在已经被难住了。

此外,以下查询也确实返回结果

select upc 
from mrs..items 
where upc not in (select upc from staging..posrecords)

既然如此,我更加困惑为什么上面的第一个查询没有返回任何结果。

4

2 回答 2

3

原因:当子查询在列中包含 NULL 值时,它总是返回 NULL。

1 OR 2 OR NULL
TRUE OR NULL
NULL

更多细节与示例。

http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/

原因可能是您的 NULL 值upc column in mrs...items table,请尝试以下查询。

    select upc 
    from   staging..posrecords 
    where  upc not in (select upc from mrs..items where upc is not null)

    select upc 
    from   staging..posrecords 
    where  upc in (select upc from mrs..items where upc is not null)

尝试使用Not exists

    select upc 
    from staging..posrecords 
    where not exists ( select upc from mrs..items 
    where mrs..items.ups = staging..posrecords.upc)


    select upc 
    from   staging..posrecords 
    where not exists(select upc from mrs..items 
    where mrs..items.upc=staging..posrecords.upc)
于 2012-06-07T05:39:18.717 回答
1

也许这只是你糟糕的一天。尝试使用 JOIN 来获取您的第一个 NOT IN 查询。像这样 -

SELECT sp.upc 
FROM staging..posrecords sp LEFT JOIN mrs..items mi 
 ON (sp.upc=mi.upc)
WHERE
 mi.upc IS NULL;
于 2012-06-07T05:49:55.967 回答