【问题标题】:How to select data from table with multiple where on the same column based on another table in SQLite如何根据SQLite中的另一个表从同一列上具有多个位置的表中选择数据
【发布时间】:2021-07-31 13:03:46
【问题描述】:

我有一个posts表,每个post都有标签,每个标签都有一个topic,例如:

Post name: Anything
Post tag: 1, 2, 3

1: is the id of Male
2: is the id of United States
3: is the id of India

1标签属于性别话题,23标签属于国家话题。

这里的表格是这样的:

posts:
 - id
 - name

tags:
 - id
 - name
 - topic_id

topics:
 - id
 - name

tags_posts:
 - tag_id
 - post_id

如果用户在 UI 上选择了 Male 和 United States,现在我想做一个这样的过滤器,所以我应该选择所有带有 Male 和 United States 标签的帖子。

SELECT * FROM posts where tag_relation = Male and tag_relation = United States

tag_relation here means JOIN to tags_posts table

但如果用户在 UI 上选择了男性、美国和印度,那么我应该选择所有具有男性和(美国或印度)标签的帖子。

SELECT * FROM posts where tag_relation = Male and (tag_relation = United States or tag_relation = India)

tag_relation here means JOIN to tags_posts table

你可以看到标签是否属于同一个主题,哪里应该是OR,但如果它们属于不同的主题,那么哪里应该是AND

所以这里的问题是我如何加入主题表并检查所选标签是否是同一主题并根据主题对所选标签进行分组,然后根据该主题执行位置。

【问题讨论】:

    标签: sql database sqlite


    【解决方案1】:

    嗯。您可以计算与每个帖子匹配的主题,然后将其与提供的标签中的主题数量进行比较。这是一种返回帖子 ID 的方法:

    select tp.post_id
    from tags t join
         tags_posts tp
         on tp.tag_id = t.id 
    where t.tag in ( . . . ) -- the list here
    group by tp.post_id
    having count(distinct t.topic_id) = (select count(distinct t2.topic_id)
                                         from tags t
                                         where t2.tag in ( . . . )  -- the list here
                                        );
    

    您可以加入posts 表以获取其他列(或使用existsin 或其他)。

    您也可以使用窗口函数来做到这一点。但是不支持count(distinct),所以可以改用dense_rank() sum 方法:

    select tp.post_id
    from (select t.*,
                 (-1 +
                  dense_rank() over (order by t.topic_id asc) +
                  dense_rank() over (order by t.topic_id desc)
                 ) as num_topics
          from tags t
          where t.tag in ( . . . )
         ) t join
         tags_posts tp
         on tp.tag_id = t.id 
    group by tp.post_id, t.num_topics
    having count(distinct t.topic_id) = t.num_topics
    

    【讨论】:

    • 您正在选择标签,我想根据标签选择帖子,in 子句在这里也不起作用,因为并非所有标签都属于同一个主题
    • @MohamedHamdan 。 . .这是选择帖子,而不是标签。
    • posts在posts表中,tags_posts只用于关系,因为标签和posts之间的关系是多对多的,所以posts在posts表中,posts和posts之间的关系标签在tags_posts 表中
    • @MohamedHamdan 。 . . post_id 应该没问题。您可以使用join 或其他方式获取其他列。这似乎不是您问题的核心。
    • 它似乎正在工作,测试它,到目前为止它返回了我需要的东西,我需要更多地测试它,你能解释一下你做了什么吗?
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多