我在PostgreSQL中有一个字符串数组:
SELECT ARRAY['dog', 'cat', 'mouse'];
我有一个大段:
Dogs and cats have a range of interactions. The natural instincts of each species lead towards antagonistic interactions, though individual animals can have non-aggressive relationships with each other, particularly under conditions where humans have socialized non-aggressive behaviors.
The generally aggressive interactions between the species have been noted in cultural expressions.
对于数组中的每个项,我想检查它是否出现在我的大段落字符串中。我知道,任何一根弦,我都可以做到以下几点:
SELECT paragraph_text ILIKE '%dog%';
但是有没有一种方法可以在不诉诸plpgsql的情况下同时检查数组中的每个字符串(对于任意数量的数组元素)?
最佳答案
我相信您需要这样的东西(假设paragraph_text
是名为table
的表中的列):
SELECT
paragraph_text,
sub.word,
paragraph_text ILIKE '%' || sub.word || '%' as is_word_in_text
FROM
table1 CROSS JOIN (
SELECT unnest(ARRAY['dog', 'cat', 'mouse']) as word
) as sub;
函数
unnest(array)
从数组值创建记录表。您可以执行CROSS JOIN
操作,这意味着table1
中的所有行都与该unest表中的所有行合并。如果
paragraph_text
是某种静态值(不是表中的值),则可以执行以下操作:SELECT
paragraph_text,
sub.word,
paragraph_text ILIKE '%' || sub.word || '%' as is_word_in_text
FROM (
SELECT unnest(ARRAY['dog', 'cat', 'mouse']) as word
) as sub;