gpt4 book ai didi

sql-server - SQL Not Exists 包含空值

转载 作者:行者123 更新时间:2023-12-04 02:05:34 27 4
gpt4 key购买 nike

我有两个 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 语句中不计算空值并显示?

最佳答案

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)
)
)

关于sql-server - SQL Not Exists 包含空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52032175/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com