Postgresql:将%追加到数组元素的开头和结尾
我的查询中有一个数组元素,需要在开始和结束时向其中添加%Postgresql:将%追加到数组元素的开头和结尾,postgresql,Postgresql,我的查询中有一个数组元素,需要在开始和结束时向其中添加% Table friends id type keywords 1 Close beverage,party,cool 2 Close party 3 Close beverage 4 Far beverage 当前我的查询: select id from friends f where f.type = 'Close' and ('BEVERAGE ALLOWED' ilik
Table friends
id type keywords
1 Close beverage,party,cool
2 Close party
3 Close beverage
4 Far beverage
当前我的查询:
select id from friends f where f.type = 'Close' and ('BEVERAGE ALLOWED' ilike any((string_to_array(f.keywords,',')))
在上面的查询中,(字符串到数组(f.keywords,,)
将关键字转换为数组,例如:{beverage,party,cool}
。
但是我需要在每个元素的开始和结束处添加%sign,这样数组元素如下:
{%beverage%,%party%,%cool%}
您可以使用它生成数组:
string_to_array('%' || replace(f.keywords, ',', '%,%') || '%', ',')
您可以使用此命令生成阵列:
string_to_array('%' || replace(f.keywords, ',', '%,%') || '%', ',')
最简单的方法是使用
~*
运算符而不是ilike
:
select id
from friends f
where
f.type = 'Close' and
('BEVERAGE ALLOWED' ~* any((string_to_array(f.keywords,',')))
或类似于:
select id
from friends f
where
f.type = 'Close' and
(upper('BEVERAGE ALLOWED') SIMILAR TO '%(' || upper(replace(f.keywords,',','|')) || ')%')
请注意,类似于的是区分大小写的,因此我们必须使用upper()
函数
但是,它不能正确地处理这样的情况
select
'foobar' ~* any(array['FOO','BAR']),
'foobar' ilike any(array['%FOO%','%BAR%']);
(两个条件都返回true
)
有很多方法可以解决这个问题。其中一种可能是:
或者,对于您的查询:
select id
from friends f
where
f.type = 'Close' and
(to_tsvector('BEVERAGE ALLOWED') @@ to_tsquery(replace(f.keywords,',','|'));
最简单的方法是使用~*
运算符而不是ilike
:
select id
from friends f
where
f.type = 'Close' and
('BEVERAGE ALLOWED' ~* any((string_to_array(f.keywords,',')))
或类似于
:
select id
from friends f
where
f.type = 'Close' and
(upper('BEVERAGE ALLOWED') SIMILAR TO '%(' || upper(replace(f.keywords,',','|')) || ')%')
请注意,类似于的是区分大小写的,因此我们必须使用upper()
函数
但是,它不能正确地处理这样的情况
select
'foobar' ~* any(array['FOO','BAR']),
'foobar' ilike any(array['%FOO%','%BAR%']);
(两个条件都返回true
)
有很多方法可以解决这个问题。其中一种可能是:
或者,对于您的查询:
select id
from friends f
where
f.type = 'Close' and
(to_tsvector('BEVERAGE ALLOWED') @@ to_tsquery(replace(f.keywords,',','|'));
我从评论中删除了我的答案-这里@Abelistoconcat('{%',replace('beverage,party,cool',',',',',','%,%,%'),'%})
我从评论中删除了我的答案-这里@Abelistoconcat('{%',replace('beverage,party,cool',',',',',',','%,%,%,'),'})