Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql:将%追加到数组元素的开头和结尾_Postgresql - Fatal编程技术网

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,',','|'));

我从评论中删除了我的答案-这里@Abelisto
concat('{%',replace('beverage,party,cool',',',',',','%,%,%'),'%})
我从评论中删除了我的答案-这里@Abelisto
concat('{%',replace('beverage,party,cool',',',',',',','%,%,%,'),'})