使用带转义符的ilike any()

时间:2019-10-18 16:22:29

标签: postgresql jdbc

在PostgreSQL中,您可以使用ILIKE进行不区分大小写的查询:

select * from test where value ilike 'half is 50$%' escape '$'

您可以通过将ILIKEANY()组合在一起一次查询多个值

select * from test where value ilike any(array['half is 50%', 'fifth is 20%'])

上面的查询将匹配我不想要的'Fifth is 2019',但是当我尝试将ILIKEANY()与转义符一起使用时,会出现语法错误。

我错过了一些愚蠢的东西吗?或者这根本不被支持吗?如果不是,是否存在另一种以不区分大小写的方式一次查询多个值的方法?

编辑:为澄清起见,该查询将通过JDBC接受参数,因此实际的SQL类似于

select * from test where value ilike any(?) escape '$'

这就是为什么我要从用户输入中将%和_解释为文字。

2 个答案:

答案 0 :(得分:1)

ESCAPE中的ILIKE子句仅引用文字,不适用于表达式。您应该使用反斜杠,或者如果不能的话,可以尝试:

with test(value) as (
values 
    ('half is 50%'),
    ('half is 50x'),
    ('fifth is 20%'),
    ('fifth is 2000')
)

select * 
from test
where value ilike any(select replace(unnest(array['half is 50$%', 'fifth is 20$%']), '$', '\'))

    value     
--------------
 half is 50%
 fifth is 20%
(2 rows)

看起来有些笨拙,但效果很好。

答案 1 :(得分:0)

要将它们作为原始字符串进行匹配,可以使用~*运算符进行不敏感的匹配。

knayak=# select 'Half is 50%' ~* any(array['half is 50%', 'fifth is 20%'])
knayak-# ;
 ?column?
----------
 t            --True
(1 row)

knayak=# select 'fifth is 20' ~* any(array['half is 50%', 'fifth is 20%']);
 ?column?
----------
 f             --False
(1 row)

如果希望转义ilike的右侧操作数,请使用“转义”字符串常量,它是SQL标准的扩展。通过在开头的单引号前写字母E(大写或小写)来指定转义字符串常量

knayak=# select 'Half is 50%' ilike any(array[E'half is 50\\%', E'half is 20\\%'])
knayak-# ;
 ?column?
----------
 t
(1 row)

DEMO