sql - PostgreSQL 根据数组值的组合选择行

标签 sql arrays postgresql select twitter

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

举个例子: 我有以下数组:

'{"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[])

所以最后一行需要以某种方式进行调整,但我不知道如何 - 也许使用内部连接?!

我在另一个表中也存储了具有唯一 ID 的单词。

我的一个 friend 建议对每一行进行计数,但我没有在原始表中添加额外列的写入权限。

背景:

我将推文存储在 postgres 数据库中,并在数据集上应用了 LDA(潜在狄利克雷分配)。现在我得到了生成的主题和与每个主题相关的单词(20 个主题和 25 个单词)。

最佳答案

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

关于sql - PostgreSQL 根据数组值的组合选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29357179/

相关文章:

sql - 需要在 SQL Server 2008 中将二进制转换为 NVARCHAR

php - 从 MySQL 查询结果创建和使用关联数组 - PHP

sql - 数据库设计 - 可空字段

postgresql - 将 RDS 连接到 Quicksight 抛出 `GENERIC_SQL_EXCEPTION`

mysql - 将 drupal 数据库从 mysql 转换为 postgresql?

mysql - SQL 在 SELECT 表中输入与实际表数据不同的数据,基于 if 语句

c# - 为什么 Contains() 运算符会如此显着地降低 Entity Framework 的性能?

sql - 如何查询UNION查询的结果

c++ - cconstructor 中的迭代器 - vector 和数组

arrays - 在 Postgres 中索引一个 jsonb 数组