2015-03-30 88 views
1

我想从我的数据库中选择所有行,其中一行至少包含一组词/数组中的两个词。PostgreSQL根据数组值选择行

作为一个例子: 我有以下的数组:

'{"test", "god", "safe", "name", "hello", "pray", "stay", "word", "peopl", "rain", "lord", "make", "life", "hope", "whatever", "makes", "strong", "stop", "give", "television"}'  

和我存储在数据库中的鸣叫数据集。所以我想知道哪些推文(列名:tweet.content)包含在至少两个的字样。

我当前的代码看起来是这样的(但当然只选择一个字......):

CREATE OR REPLACE VIEW tweet_selection AS 
SELECT tweet.id, tweet.content, tweet.username, tweet.geometry, 
FROM tweet 
WHERE tweet.topic_indicator > 0.15::double precision 
AND string_to_array(lower(tweet.content)) = ANY(SELECT '{"test", "god", "safe", "name", "hello", "pray", "stay", "word", "peopl", "rain", "lord", "make", "life", "hope", "whatever", "makes", "strong", "stop", "give", "television"}'::text[]) 

所以最后一行需要以某种方式adjustested,但我不知道如何 - 也许有一个内部连接?

我的单词也存储在一个不同的表中唯一的ID。

我的一位朋友推荐为每一行获取一个计数,但是我没有在原始表中添加额外列的写入权限。

背景:

我储存我的tweets在Postgres数据库和我申请的数据集LDA(隐含狄利克雷分配)。现在我得到了生成的主题和与每个主题相关的单词(20个主题和25个单词)。

+0

@mu太短 ID = _integer_ – user3815852 2015-03-30 23:26:00

+0

@mu太短数据库的 标准的公共架构...鸣叫** ID = _integer_ 用户id = _bigint_的 **结构 用户名= _text_ tweetcontent_raw = _text_ tweetcontent = _text(梗鸣叫) tweetdate = _timestamp随时间zone_ the_geom = _geometry_ 哪里的话都存储在表(results_lda): OID topic_id = _integer_ 字= _text_ topic_probability = _double precision_ – user3815852 2015-03-30 23:35:12

+0

SRY我的会议得到了中断 – user3815852 2015-03-30 23:35:26

回答

0
select DISTINCT ON (tweet.id) tweet.id, tweet.content, tweet.username, tweet.geometry 
from tweet 
where 
    tweet.topic_indicator > 0.15::double precision 
    and (
     select count(distinct word) 
     from 
      unnest(
       array['test', 'god', 'safe', 'name', 'hello', 'pray', 'stay', 'word', 'peopl', 'rain', 'lord', 'make', 'life', 'hope', 'whatever', 'makes', 'strong', 'stop', 'give', 'television']::text[] 
      ) s(word) 
      inner join 
      regexp_split_to_table(lower(tweet.content), ' ') v (word) using (word) 
    ) >= 2 
+0

非常感谢!这解决了问题:)我加了 'SELECT DISTINCT ON(tweet.id)tweet.id,tweet.content ....' 否则有重复的条目...非常感谢:) – user3815852 2015-03-31 11:23:34