来自NOT IN子查询的奇怪结果

时间:2016-04-18 13:18:15

标签: sql-server

我有这个简单的查询:

SELECT COUNT(SalesOrderId)
FROM SalesOrder

结果为14000

然后我

SELECT COUNT(SalesOrderId)
FROM SalesOrder
WHERE SalesOrderId     IN (SELECT New_DSheetId FROM New_dealsheet)

这给了4169

如果我那么做

SELECT COUNT(SalesOrderId)
FROM SalesOrder
WHERE SalesOrderId NOT IN (SELECT New_DSheetId FROM New_dealsheet) 

我期待9831,但结果是0

不确定为什么会这样?

2 个答案:

答案 0 :(得分:2)

NOT IN的{​​p> NULL可能会非常棘手。

让我们打开它:

col IN (1,2,3, NULL)
<=>
(col = 1) OR (col = 2) OR (col = 3) OR (col = NULL)

现在一切都好。但事实并非如此。我们无法直接将值与NULL进行比较,因为结果为unknown

让我们检查否定条件:

col NOT IN (1,2,3,NULL)
<=>
(col != 1) AND (col != 2) AND (col != 3) AND (col != NULL) 
                                              -- here is the problem

LiveDemo

总结最后一个条件总是不正确。这就是你得到0条记录的原因。

使用NOT IN时,请确保不与NULL值进行比较。

答案 1 :(得分:1)

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
    )