首页 > 解决方案 > 当PostgreSQL中的where子句为空时,如何不依赖于where子句中的条件进行查询?

问题描述

我想进行一个查询,当条件为空时,结果不取决于 where 子句中的条件,而当条件不为空时,结果取决于条件。

我提出的一个查询是

select * from mytable where (num_lot = :num_lot or :num_lot is null) and date_work between :date_start and :date_stop

:num_lot为空时,结果不取决于我想要的 num_lot。但是:date_start并且:date_stop为空,没有返回任何行,而不是不依赖于:date_start 和:date_stop。

标签: postgresqlnullwhere-clause

解决方案


SELECT * FROM mytable WHERE
    num_lot=COALESCE(:num_lot,num_lot) AND
    date_work BETWEEN COALESCE(:date_start,date_work) and COALESCE(:date_stop,date_work)

当验证值为 NULL 时,它被替换为列值,即始终为真。


推荐阅读