今天使用SQL Server 时,遇到使用not in 和not exist的查询结果有差异:not in 查询没结果。
原因:not in 遇到null就不工作了。
摘录:
SELECT foreignStockId
FROM[Subset].[dbo].[Products]
Probably returns a NULL
. Try
SELECT stock.IdStock
,stock.Descr
FROM[Inventory].[dbo].[Stock] stock
WHERE stock.IdStock NOTIN(SELECT foreignStockId FROM[Subset].[dbo].[Products]WHERE foreignStockId ISNOTNULL)
a NOT IN (x,y,NULL)
Will always return no results as it is equivalent to
a<>x and a<>y and a<>NULL
which is
true and true and unknown
Which evaluates to unknown
under the rules of three valued logic.
I normally use NOT EXISTS
for this type of query
SELECT stock.idstock,
stock.descr
FROM[Inventory].[dbo].[Stock] stock
WHERENOTEXISTS(SELECT*FROM[Subset].[dbo].[Products] p
WHERE p.foreignstockid = stock.idstock)
原文网址:
http://stackoverflow.com/questions/5231712/sql-not-in-not-working