在涉及“Null”的 SQL 查询中感到困惑返回未选择的行
我对这两个 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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SQL 使用三值逻辑(
True
、False
、Unknown
)。WHERE
子句需要计算为True
才能返回行。当
Status IS NULL
时,STATUS = 'PENDING'
返回UNKNOWN
。如果您否定
Unknown
,您仍然会得到Unknown
。请参阅 SQL和三值逻辑的圈套
您需要将查询重写为
(尽管可以使用已弃用的
ANSI_NULLS
会话选项来获得您想要的行为)SQL uses three valued logic (
True
,False
,Unknown
). TheWHERE
clause needs to evaluate toTrue
for a row to be returned.STATUS = 'PENDING'
returnsUNKNOWN
whenStatus IS NULL
.If you negate
Unknown
you still getUnknown
.See SQL and the Snare of Three-Valued Logic
You would need to rewrite the query as
(Though it is possible to use the deprecated
ANSI_NULLS
session option to get the behaviour you want)