postgresql - 如何检查 Postgres 中的字符串不等式

标签 postgresql

这怎么可能?

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/

相关文章:

postgresql ON CONFLICT ON CONSTRAINT for 2 constraints

sql - 具有深层次结构的非常慢的 postgresql 查询

sql - 删除表某列中后续的重复字符串

python - 插入不使用 Python 的数据库表

ruby-on-rails - rails 4 : When is a database connection established?

postgresql - 在 PostgreSQL 8.4 中安装附加模块立方体时遇到问题

php - PostgreSQL 没有出现在 phpconfig() 函数中(在 Windows 上)

postgresql - 新的 Heroku pg :backups public-url provide? 是什么类型的文件

postgresql - Postgres : MD5 Password/Plain password

database - Azure Database for PostgreSQL 的匿名化/数据屏蔽