sql - PostgreSQL: "select where"查询过滤掉具有 [null] 值的记录

标签 sql postgresql

当我运行以下简单查询时:

SELECT gateway, customer_id
FROM gateways
where gateway = '1000056'

这是它返回的记录,显示 [null] 客户 ID:

PostgreSQL record showing null customer_id

当我添加另一个过滤器时,不再返回记录,但我认为它应该仍然返回,因为customer_id是< em>不等于21:

SELECT gateway, customer_id
FROM gateways
where gateway = '1000056'
    and customer_id != 21 --new filter!

不再返回记录:

record no longer return; zero records returned

如何过滤掉 customer_id = 21 的记录,但仍返回该 customer_id = [null] 的记录?

最佳答案

我找到了答案here 。这是该答案的直接引用:

In SQL, NULL is not equal to anything. Nor is it unequal to anything.

In other words, if I don't tell you my middle name, and you don't tell me your middle name, how can we know if our two middle names are the same name or different names? We can't know.

This often trips people up in SQL, because it's "tri-value logic." An expression can be TRUE, FALSE, or UNKNOWN. Those of us familiar with boolean algebra know that NOT TRUE is FALSE, and NOT FALSE is TRUE.

But the tricky part is that NOT UNKNOWN is still UNKNOWN.

So the solution for you is either always store a non-null string in your column, or else use an expression to account for tri-value logic

这有效:

SELECT gateway, customer_id
FROM gateways
where gateway = '1000056'
    and customer_id is distinct from 21

返回我想要的记录: the record I want to be returned

关于sql - PostgreSQL: "select where"查询过滤掉具有 [null] 值的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69396940/

相关文章:

java - 将数据从 arraylist 插入表

postgresql - 错误: syntax error at or near "(" when creating a new table

sql - 右外连接没有得到相同的结果不知道为什么 (=*)

mysql - 模式迁移 : one-to-many, PostgreSQL 中的多对多

sql - ActiveRecord:按组计数

sql - 如何在 Firebird 的两个不同表中获得两个不同的总数? (使用左外连接连接 3 个表)

python - Django 服务器不会在 Docker-Compose 中启动

postgresql - 数据库触发器限制 Postgres 中的最大表大小

sql - 在所有列中搜索并找到一个字符串值

sql - HTML5 Web 数据库安全