基于两个多对多关系选择行

时间:2019-08-15 18:46:27

标签: sql postgresql join many-to-many

我有三个表:producttagtag_collection(还有两个联结表)(标签集合是一组命名的标签)

My table layout 现在,假设我有一个名为sugar free cola的标签集合,其ID为1,并且与它们关联的标签有:sodacola,{{1} }。

我有一些ID为sugar free45的产品,它们具有与之相关的相同标签。

要从tag_collection ID 6获得产品456的情况下,我必须使用哪种查询。

换句话说,如何获得在给定的tag_collection中具有的所有标签的产品?

我尝试对每个表使用1进行查询,但这为我提供了在LEFT JOIN中具有标签之一的产品。

我正在使用Postgresql 11.1。

1 个答案:

答案 0 :(得分:1)

您可以将两个联结表连接在一起。然后汇总并计算标签:

select pt.product_id
from product_tags pt join
     (select tct.*, count(*) over (partition by tct.tag_collection_id) as cnt
      from tag_collection_tag tct 
     ) tct
     on tct.tag_id = pt.tag_id
where tct.tag_collection_id = 1
group by pt.product_id, tct.cnt
having count(*) = tct.cnt  -- number of matches equals the number of tags