[英]Adding conditions to where clause
How would I write a sql statement that only includes conditions in a where clause if the param has a value (i only want to include the field2 check in the where clause if the param has a valid value)如果参数具有值,我将如何编写仅包含 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
A typical method uses or
with explicit NULL
comparisons for the parameter:一个典型的方法使用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) ;
If you specifically wanted white space to behave the same as NULL
s, then this gets more complicated.如果您特别希望空格的行为与NULL
相同,那么这会变得更加复杂。 Something like:就像是:
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) ;
However, I think it would be more common to turn blank strings into NULL
s before passing in the parameter, so the SQL would only be working with NULL
as a special value.但是,我认为在传入参数之前将空字符串转换为NULL
会更常见,因此 SQL 只会将NULL
作为特殊值使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.