当 PostgreSQL 中的 where 子句为空时,如何不依赖于条件进行查询?

how to make a query not depending on the conditions in where clause when they are null in PostgreSQL?

我想做一个查询,当条件为空时,结果不取决于 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为null时,结果不依赖于num_lot,这正是我想要的。 但是 :date_start:date_stop 为空,没有返回任何行而不是不依赖于 :date_start 和 :date_stop.

使用coalesce()检查:date_start:date_stop是否都是null:

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

或:

select * 
from mytable 
where (num_lot = :num_lot or :num_lot is null) 
and ((date_work between :date_start and :date_stop) or (:date_start is null and  :date_stop is null))
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 时,它将替换为列值,即始终为真。