2016-12-13 11 views
0

私は配列の要素をクエリの中に入れて、開始時と終了時に%を追加する必要があります。Postgresql:配列要素の先頭と末尾に%を付加します。

Table friends 
id type keywords 
1 Close beverage,party,cool 
2 Close party 
3 Close beverage 
4  Far  beverage 

現在、私のクエリ:{beverage,party,cool}:上記のクエリ(string_to_array(f.keywords,','))

select id from friends f where f.type = 'Close' and ('BEVERAGE ALLOWED' ilike any((string_to_array(f.keywords,','))) 

は、次のような配列にキーワードを変換します。 しかし、私はのように配列の要素があるように、各要素の開始と終了に%記号を追加する必要があります:あなたは、あなたの配列を生成するためにこれを使用することができます{%beverage%,%party%,%cool%}

+0

私は私の答えを削除 - ここでは 'CONCAT( '{%'、( '飲料、パーティーを交換、クール@Abelisto '、'、 '、'%、% ')、'%} ')コメントから –

答えて

2

string_to_array('%' || replace(f.keywords, ',', '%,%') || '%', ',') 
2

最も簡単な方法はにあります~*オペレータの代わりilikeを使用:

select id 
from friends f 
where 
    f.type = 'Close' and 
    ('BEVERAGE ALLOWED' ~* any((string_to_array(f.keywords,','))) 

Doc

またはSIMILAR TOSIMILAR TOは大文字と小文字が区別されますので、我々はupper()機能を使用する必要があること

select id 
from friends f 
where 
    f.type = 'Close' and 
    (upper('BEVERAGE ALLOWED') SIMILAR TO '%(' || upper(replace(f.keywords,',','|')) || ')%') 

Doc

注意。

しかし、それを解決するためにどのような方法はたくさんあります(両方condidionsがtrueを返す)

select 
    'foobar' ~* any(array['FOO','BAR']), 
    'foobar' ilike any(array['%FOO%','%BAR%']); 

のように適切にケースを処理しません。可能性の一つ:Text Search

select 
    to_tsvector('FOOBAR') @@ to_tsquery('foo|bar'), 
    to_tsvector('FOO BAR') @@ to_tsquery('foo|bar'); 

または、クエリの:

select id 
from friends f 
where 
    f.type = 'Close' and 
    (to_tsvector('BEVERAGE ALLOWED') @@ to_tsquery(replace(f.keywords,',','|')); 
関連する問題