向 where 子句添加条件
Posted
技术标签:
【中文标题】向 where 子句添加条件【英文标题】:Adding conditions to where clause 【发布时间】:2021-07-19 11:58:47 【问题描述】:如果参数具有值,我将如何编写仅在 where 子句中包含条件的 sql 语句(如果参数具有有效值,我只想在 where 子句中包含 field2 检查)
SELECT * FROM abc
WHERE if(:param1 has a value that is not null or white space) then field1 = :param1
AND if(:param2 has a value that is not null or white space) then field2 = :param2
AND if(:param3 has a value that is not null or white space) then field3 = :param3
AND if(:param4 has a value that is not null or white space) then field4 = :param4
AND if(:param5 has a value that is not null or white space) then field5 = :param5
【问题讨论】:
(field1 = :param1 or :param1 is null or :param1 = ' ')
不太理解“或”的逻辑。你能简单解释一下吗?
【参考方案1】:
一种典型的方法是使用or
和显式NULL
比较参数:
SELECT *
FROM abc
WHERE (:param1 is null OR field1 = :param1) AND
(:param2 is null OR field2 = :param2) AND
(:param3 is null OR field3 = :param3) AND
(:param4 is null OR field4 = :param4) AND
(:param5 is null OR field5 = :param5) ;
如果您特别希望空白的行为与NULL
s 相同,那么这会变得更加复杂。比如:
WHERE (NULLIF(REPLACE(:param1, ' '), '') is null OR field1 = :param1) AND
(NULLIF(REPLACE(:param2, ' '), '') is null OR field2 = :param2) AND
(NULLIF(REPLACE(:param3, ' '), '') is null OR field3 = :param3) AND
(NULLIF(REPLACE(:param4, ' '), '') is null OR field4 = :param4) AND
(NULLIF(REPLACE(:param5, ' '), '') is null OR field5 = :param5) ;
但是,我认为在传入参数之前将空白字符串转换为NULL
s 会更常见,因此 SQL 只能使用 NULL
作为特殊值。
【讨论】:
以上是关于向 where 子句添加条件的主要内容,如果未能解决你的问题,请参考以下文章