[英]Strange results from NOT IN subquery
I have this simple query: 我有这个简单的查询:
SELECT COUNT(SalesOrderId)
FROM SalesOrder
It gives a result of 14000 它给出了14000的结果
Then I have 然后我有
SELECT COUNT(SalesOrderId)
FROM SalesOrder
WHERE SalesOrderId IN (SELECT New_DSheetId FROM New_dealsheet)
That gives 4169 这给了4169
If I then do 如果我那么做
SELECT COUNT(SalesOrderId)
FROM SalesOrder
WHERE SalesOrderId NOT IN (SELECT New_DSheetId FROM New_dealsheet)
I'm expecting 9831 but the result is 0 我期待9831,但结果是0
Not sure why that is? 不知道为什么会这样?
NOT IN
with NULL
could be tricky. NOT IN
with NULL
可能很棘手。
Let's unwrap it: 我们打开它:
col IN (1,2,3, NULL)
<=>
(col = 1) OR (col = 2) OR (col = 3) OR (col = NULL)
For now everything is ok. 现在一切都好。 But it isn't.
但事实并非如此。 We cannot compare directly value to
NULL
because the result is unknown
. 我们无法直接将值与
NULL
进行比较,因为结果unknown
。
Let's check negated condition: 让我们检查否定条件:
col NOT IN (1,2,3,NULL)
<=>
(col != 1) AND (col != 2) AND (col != 3) AND (col != NULL)
-- here is the problem
To sum up last condition is always not true. 总结最后的条件总是不正确的。 That is why you get 0 records.
这就是你得到0条记录的原因。
When you use NOT IN
make sure that you do not compare with NULL
value. 使用
NOT IN
,请确保不与NULL
值进行比较。
SELECT COUNT_BIG(s.SalesOrderId)
FROM dbo.SalesOrder s
WHERE s.SalesOrderId NOT IN
(
SELECT n.New_DSheetId
FROM dbo.New_dealsheet n
WHERE n.New_DSheetId IS NOT NULL
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.