gpt4 book ai didi

SQL 查询问题 : SELECT . .. NOT IN

转载 作者:行者123 更新时间:2023-12-01 18:34:31 26 4
gpt4 key购买 nike

我肯定犯了一个愚蠢的错误,但我不知道是什么:

在 SQL Server 2005 中,我尝试选择除凌晨 2 点之前预订的客户之外的所有客户。

当我运行此查询时:

SELECT idCustomer FROM reservations 
WHERE idCustomer NOT IN
(SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2)

我得到 0 个结果。

但是

SELECT idCustomer FROM reservations 

返回 152.000 个结果和“NOT IN”部分:

SELECT distinct idCustomer FROM reservations 
WHERE DATEPART ( hour, insertDate) < 2

仅返回 284 行

最佳答案

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
and idCustomer is not null

确保您的列表参数不包含空值。

这里有一个解释:

WHERE field1 NOT IN (1, 2, 3, null)

等同于:

WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
  • 最后一次比较的结果为 null。
  • 该 null 与 bool 表达式的其余部分进行“或”运算,得到 null。 (*)
  • null 被否定,产生 null。
  • null 不为 true - where 子句仅保留 true 行,因此所有行都会被过滤。

(*) 编辑:这个解释非常好,但我想解决一件事以避免将来的挑剔。 (TRUE OR NULL) 将计算为 TRUE。例如,如果 field1 = 3,则这是相关的。该 TRUE 值将被否定为 FALSE,并且该行将被过滤。

关于SQL 查询问题 : SELECT . .. NOT IN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/296146/

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