在这里找到我问题的最佳答案:NOT IN clause and NULL values
以下两个查询都不会返回任何结果:
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)
在这种情况下,我更加困惑的是为什么上面的第一个查询不会返回任何结果。
答案 0 :(得分: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/
原因可能是upc column in mrs...items table
中有NULL值,请尝试以下查询。
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)
答案 1 :(得分: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;