为什么我的查询无法按预期运行?

时间:2016-11-14 16:46:34

标签: sql-server tsql notin

我有一个查询,我正在尝试获取特定值,而不是在其他表中,但是当我运行查询时,我没有得到任何结果。这就是我所看到的。请让我知道出了什么问题。

原始查询:返回399行

        USE TFW_DEV

    SELECT
       unitid, unitnumber
     FROM
       Units
     WHERE 
        createdon BETWEEN '2016-11-01 00:00:00' AND '2016-11-03 23:59:59'
    ORDER BY
        unitnumber

查询表共享数据的位置:返回50行

USE TFW_DEV

SELECT
   unitid, unitnumber
 FROM
   Units
 WHERE 
    createdon BETWEEN '2016-11-01 00:00:00' AND '2016-11-03 23:59:59'
    AND unitid  IN
    (
        SELECT
            unitid
        FROM
            meteraudit      
    )
ORDER BY
    unitnumber

使用NOT IN的最终查询:返回0行

USE TFW_DEV

SELECT
   unitid, unitnumber
 FROM
   Units
 WHERE 
    createdon BETWEEN '2016-11-01 00:00:00' AND '2016-11-03 23:59:59'
    AND unitid NOT IN
    (
        SELECT
            unitid
        FROM
            meteraudit      
    )
ORDER BY
    unitnumber

我希望最终查询返回349行是否正确?如果不是我做错了什么?谢谢,

1 个答案:

答案 0 :(得分:3)

NULL

返回Sub-Query值时,

NOT EXISTS失败

使用SELECT unitid, unitnumber FROM units U WHERE createdon BETWEEN '2016-11-01 00:00:00' AND '2016-11-03 23:59:59' AND NOT EXISTS (SELECT 1 FROM meteraudit M WHERE U.unitid = M.unitid) ORDER BY unitnumber

{{1}}