我有一个 SQL 脚本,在 If Null 语句中使用通配符。 我希望显示所有其他记录,无论字段中是否有空值。
SELECT * FROM ABC WHERE (Value=1 AND
Prefix like IFNULL(${parameter:X},'%')
AND
Base like IFNULL(${parameter:Y},'%')
AND
Suffix like IFNULL(${parameter:Z},'%')
AND
Area like IFNULL(${parameter:Ax},'%')
);
我期望结果应该显示所有值,无论区域字段值是否为空
最佳答案
不要使用like
。它将过滤掉数据中的NULL
值。只要这样做:
WHERE (NewestVersion = 1 AND
(Prefix like ${param:PrefixLookup} or ${param:PrefixLookup} is null) AND
(Base like ${param:BaseLookup} or ${param:BaseLookup} is null) AND
(Suffix like ${param:SuffixLookup} or ${param:SuffixLookup} is null) AND
(Custom2 like ${param:DRELookup} or ${param:DRELookup} is null)
如果您有空字符串,则与 NULL
的比较将无济于事。只需使用:
WHERE (NewestVersion = 1 AND
(Prefix like ${param:PrefixLookup} or ${param:PrefixLookup} = '') AND
(Base like ${param:BaseLookup} or ${param:BaseLookup} = '') AND
(Suffix like ${param:SuffixLookup} or ${param:SuffixLookup} = '') AND
(Custom2 like ${param:DRELookup} or ${param:DRELookup} = '')
关于MySQL 函数 IFNULL 无法与通配符一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57414767/