PostgreSQL:检查数组中的每个项是否包含在较大的字符串中

PostgreSQL:检查数组中的每个项是否包含在较大的字符串中,sql,arrays,postgresql,sql-like,Sql,Arrays,Postgresql,Sql Like,我在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 relatio

我在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的情况下同时检查数组中的每个字符串(任意数量的数组元素)

我相信您想要这样的内容(假设
段落_text
是表中名为
table
的列):

函数
unnest(array)
从数组值创建记录表。您可以执行
交叉联接
,这意味着
表1
中的所有行都与该非最新表中的所有行合并

如果
段落\u 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;

此解决方案仅适用于postgres 8.4及以上版本,因为早期版本不提供此解决方案

drop table if exists t;
create temp table t (col1 text, search_terms text[] );
insert into t values
   ('postgress is awesome', array['postgres', 'is', 'bad']), 
   ('i like open source', array['open', 'code', 'i']), 
   ('sql is easy', array['mysql']);

drop table if exists t1;
select *, unnest(search_terms) as search_term into temp t1 from t;

-- depending on how you like to do pattern matching. 
-- it will look for term not whole words
select *, position(search_term in col1) from t1;


-- This will match only whole words.
select *, string_to_array(col1, E' ')@>string_to_array(search_term, E' ') from t1;
基本上,您需要将搜索词数组展平为一列,然后将长字符串与每个搜索词逐行匹配。

谢谢--
交叉连接
是个好主意。
drop table if exists t;
create temp table t (col1 text, search_terms text[] );
insert into t values
   ('postgress is awesome', array['postgres', 'is', 'bad']), 
   ('i like open source', array['open', 'code', 'i']), 
   ('sql is easy', array['mysql']);

drop table if exists t1;
select *, unnest(search_terms) as search_term into temp t1 from t;

-- depending on how you like to do pattern matching. 
-- it will look for term not whole words
select *, position(search_term in col1) from t1;


-- This will match only whole words.
select *, string_to_array(col1, E' ')@>string_to_array(search_term, E' ') from t1;