在PostgreSQL中,当where子句中的条件为空时,如何不依赖于where子句中的条件进行查询?
我想做一个查询,当条件为null时,结果不取决于where子句中的条件,而当条件不为null时,结果取决于条件 我提出的一个问题是在PostgreSQL中,当where子句中的条件为空时,如何不依赖于where子句中的条件进行查询?,postgresql,null,where-clause,Postgresql,Null,Where Clause,我想做一个查询,当条件为null时,结果不取决于where子句中的条件,而当条件不为null时,结果取决于条件 我提出的一个问题是 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\u start和:date\u stop为
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\u start
和:date\u stop
为空,没有返回任何行,而不是依赖于:date\u start和:date\u stop。用于检查:date\u start
和:date\u stop
是否都为空:
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)
或:
当验证值为空时,它将替换为列值,即始终为真。@i486问题在于当参数:num\u lot和:date\u start和:date\u stop为空时,不依赖于它们。因此,如果它们都为null,那么查询应该返回表中的所有行。如果only:date\u start和:date\u stop为空,则查询应返回仅满足以下条件的所有行:其中num\u lot=:num\u lot
确定,我删除了我的注释。在我的评论发送后,请阅读问题的最后几行。为什么:date\u start为null,而:date\u stop为null
而不是它们之间的或
?我从您那里了解到,如果条件等于列名(即date\u work=date\u work),它将返回所有符合where子句的行。我说的对吗?如果您有类似于其中1=1
或其中col_1=col_1
的条件,则将选择SELECT
中的所有行。这里使用COALESCE
的思想是在NULL的情况下返回正确的值以获得正结果。在MS-SQL中有一个ISNULL()
函数,它的工作原理类似于COALESCE
,有两个参数,但它较短。@i486,其中col_1=col_1不返回表中的所有行,如果col_1包含空值。@forpas我同意,但在这个问题中,这种情况是不可能的。否则,date\u-work-BETWEEN…
在date\u-work
为空时也将跳过该行。@i486我们不知道是否会出现这种情况。这就是为什么必须避免这种情况。
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)