在涉及“Null”的 SQL 查询中感到困惑返回未选择的行

发布于 2024-12-11 10:07:15 字数 511 浏览 0 评论 0原文

我对这两个 SQL 查询的结果感到困惑。给出表格内容和两个查询:

Col1 Status
---- ------ 
abcd "null"
abcd PENDING
defg "null"
defg PENDING

a) SELECT Col1, STATUS FROM TABLE_A WHERE KEY IN ('abcd','defg');

b) SELECT Col1, STATUS FROM TABLE_A WHERE KEY IN ('abcd','defg') 和 NOT (STATUS = 'PENDING')

(a) 的结果显示所有 4 行,(b) 的结果显示什么也没显示!

“状态”列可以具有“PENDING”以外的值,并且出于报告原因,我不能使用“STATUS IS NOT NULL”作为过滤器。我无法理解为什么查询 (b) 什么也不返回。预先感谢您的任何帮助

平台:MSSQL 2008

I'm confused by the result of the two SQL queries. Give the table content and two queries:

Col1 Status
---- ------ 
abcd "null"
abcd PENDING
defg "null"
defg PENDING

a) SELECT Col1, STATUS FROM TABLE_A WHERE KEY IN ('abcd','defg');

b) SELECT Col1, STATUS FROM TABLE_A WHERE KEY IN ('abcd','defg') and NOT (STATUS = 'PENDING')

result of (a) shows all 4 rows, and result of (b) shows nothing!

Column 'Status' can have values other than 'PENDING', and for reporting reason, I cannot use 'STATUS IS NOT NULL' as filter. I CANNOT understand why query (b) return nothing. Thanks in advance for any help

Platform: MSSQL 2008

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阪姬 2024-12-18 10:07:15

SQL 使用三值逻辑(TrueFalseUnknown)。 WHERE 子句需要计算为 True 才能返回行。

Status IS NULL 时,STATUS = 'PENDING' 返回 UNKNOWN

如果您否定Unknown,您仍然会得到Unknown

请参阅 SQL和三值逻辑的圈套

您需要将查询重写为

SELECT Col1, STATUS 
FROM TABLE_A 
WHERE KEY IN ('abcd','defg') and (STATUS IS NULL OR  STATUS  <> 'PENDING')

(尽管可以使用已弃用的ANSI_NULLS会话选项来获得您想要的行为)

SQL uses three valued logic (True, False, Unknown). The WHERE clause needs to evaluate to True for a row to be returned.

STATUS = 'PENDING' returns UNKNOWN when Status IS NULL.

If you negate Unknown you still get Unknown.

See SQL and the Snare of Three-Valued Logic

You would need to rewrite the query as

SELECT Col1, STATUS 
FROM TABLE_A 
WHERE KEY IN ('abcd','defg') and (STATUS IS NULL OR  STATUS  <> 'PENDING')

(Though it is possible to use the deprecated ANSI_NULLS session option to get the behaviour you want)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文