这怎么可能?
select count(*) from happiness where source = 'love';
-[ RECORD 1 ]
count | 0
select count(*) from happiness where source != 'love';
-[ RECORD 1 ]
count | 9279
select count(*) from happiness;
-[ RECORD 1 ]---
count | 1418962...
还有\d
source | character varying(255) |
当我得到这个问题的答案时,我会狠狠地打自己的脸。
最佳答案
SQL 使用所谓的“三值”逻辑,其中给定的 bool 表达式可以是“true”、“false”或“null”。这种形式的查询:
select count(*) from happiness where ...;
只会返回...
为“true”的记录,跳过为“false”或“null”的记录。
当source
为null时,source = 'love'
和source != 'love'
都为null;因此,两个版本的查询都将跳过 source
为 null 的任何记录。 (NOT (source = 'love')
也将为 null:not
"true"为 "false",而 not
"false"为“true”,但 not
null 仍然为 null。)
出现此行为的原因是 null
代表“未知”;如果 source
为 null,则无法知道它是“真的”应该是 'love'
,还是“真的”应该是其他东西。 (我认为我们倾向于将 null 视为一个独特的值,与所有其他值不同,但这不是它的预期含义。)
您可能想要的是:
select count(*) from happiness where source is null or source != 'love';
关于postgresql - 如何检查 Postgres 中的字符串不等式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385934/