【问题标题】:SQL query to select all the articles with the given tags from a pivot tableSQL 查询从数据透视表中选择具有给定标签的所有文章
【发布时间】:2020-12-17 14:11:43
【问题描述】:

我在 PostgreQL 13 中有一个 article 表和一个 tag 表。articletag 具有多对多关系。使用以下架构创建数据透视表 article_tag

- FOREIGN KEY article_id REFERENCES article(id)
- FOREIGN KEY tag_id REFERENCES tag(id)

现在给定一个标签 ID 列表(ID1、ID2、ID3...),我如何查询所有具有这些标签的文章?我想过使用类似的东西:

SELECT article_id FROM (
  SELECT article_id FROM article_tag WHERE tag_id = ID2
) WEHRE tag_id = ID1;

但是如果标签id列表很长,这个查询会嵌套复杂。

【问题讨论】:

    标签: sql postgresql many-to-many


    【解决方案1】:

    你可以使用聚合:

    select article_id
    from article_tag
    where tag_id in (id1, id2, id3)
    group by article_id
    having count(*) = 3;
    

    注意3in 列表的大小。您也可以使用数组来表达这一点,这样可以简化查询:

    select article_id
    from article_tag
    where tag_id = any (:id_array)
    group by article_id
    having count(*) = cardinality(:id_array);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      相关资源
      最近更新 更多