SQL 查询 select 数据透视表中具有给定标签的所有文章 table

SQL query to select all the articles with the given tags from a pivot table

我在 PostgreQL 13 中有一个 article table 和一个 tag table。articletag 有一个多对- 多关系。使用以下架构创建枢轴 table 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;

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

您可以使用聚合:

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);