SQL不存在包含空值

时间:2018-08-27 03:25:04

标签: sql-server sql-server-2014

我有两个SQL Server表:

表1

Id name   description     version
----------------------------------
1  Book1  Book 1 Title    v1
2  Book2  Book 2 Title    v2
3  Book3  Book 3 Title    NULL
4  Book5  Book 5 Title    v3

表2

Id name   description     version
----------------------------------
1  Book1  Book 1 Title    v1
2  Book2  Book 2 Title    v2
3  Book3  Book 3 Title    NULL
4  Book4  Book 4 Title    NULL
5  Book5  Book 5 Title    NULL

我想从表2中选择表1中不存在的所有数据,所以我可以 将它们插入另一个表中。

这是SQL查询:

SELECT t2.name, t2.description, t2.version
FROM Table2 AS t2
WHERE  
    NOT EXISTS (SELECT t1.name, t1.description, t1.version 
                FROM Table1 as t1 
                WHERE t2.name = t1.name 
                  AND t2.description = t1.description  
                  AND t2.version = t1.version)

预期结果是这样的:

Id name   description     version
-----------------------------------
4  Book4  Book 4 Title    NULL
5  Book5  Book 5 Title    NULL

但是我得到的却是这个:

Id name   description     version
---------------------------------
3  Book3  Book 3 Title    NULL
4  Book4  Book 4 Title    NULL

为什么在我的NOT EXIST语句中不评估空值并显示空值?

4 个答案:

答案 0 :(得分:2)

与任何内容进行比较时,

NULL值将返回FALSE。您将需要使用IS NULL来处理

select t2.name, t2.description, t2.version
from   Table2 as t2
WHERE  NOT EXISTS 
       ( 
            SELECT *
            FROM   Table1 as t1 
            WHERE  t2.name        = t1.name 
            AND    t2.description = t1.description 
            AND    (
                       t2.version     = t1.version
                   OR  (t2.version IS NULL AND t1.version IS NULL)
                   )
       )

答案 1 :(得分:1)

您可以使用EXCEPT解决此问题。 您可以在两个表中使用一个公共字段,然后从该结果中选择数据。

看下面的代码:

SELECT name, description, version FROM Table2
EXCEPT
SELECT name, description, version FROM Table1

此代码为您提供table2中存在的,table1中不存在的数据。

答案 2 :(得分:1)

优化查询:

SELECT t2.name, t2.description, t2.version 
FROM Table2 AS t2
LEFT JOIN Table1 AS t1 
ON t2.name = t1.name 
 AND t2.description = t1.description  
 AND (t2.version     = t1.version
     OR  (t2.version IS NULL AND t1.version IS NULL))
WHERE t1.ID is NULL

答案 3 :(得分:0)

您可以简单地使用ISNULL()函数:

SELECT t2.name, t2.description, t2.version
FROM Table2 AS t2
WHERE  
    NOT EXISTS (SELECT t1.name, t1.description, t1.version 
                FROM Table1 as t1 
                WHERE t2.name = t1.name 
                  AND t2.description = t1.description  
                  AND ISNULL(t2.version,0) = ISNULL(t1.version,0)