首页 > 解决方案 > Postgres 有必要在这个 where 子句中包含两个谓词吗?

问题描述

我想编写一个查询,它返回所有action1不是的行't'(包括实例 where action1is null

此查询不返回null记录:

select * 
from actions 
where action1 <> 't'

这个查询确实返回了null记录,但我很惊讶这两个谓词都是必要的

select *
from event_actions
where action_c2 is null or action_c2 <> 't'

有没有办法在没有两个谓词的情况下编写这个查询?

标签: postgresql

解决方案


您可以IS DISTINCT FROM在比较中使用该构造,它将其视为null不同于任何非空值的已知值,即

select * 
from actions 
where action1 is distinct from 't'

a is distinct from b相当于

case 
 when a is null then b is null 
 else a is not null then b is not null and a = b 
end

供参考:https ://wiki.postgresql.org/wiki/Is_distinct_from


推荐阅读