SQL query to select posts belonging to multiple categories

前端 未结 2 588
轮回少年
轮回少年 2021-01-07 07:54

I am writing a web application similar to a blogging software. There are three tables as below

Posts Table: Post_id,Post_Text
Post_Tags Table: Post_id,Tag_i         


        
2条回答
  •  感动是毒
    2021-01-07 08:22

    This is relational division.

    Use GROUP BY and COUNT or double NOT EXISTS.

    An example of the first approach would be.

    SELECT pt.Post_id, p.Post_Text
    FROM Post_Tags pt
    JOIN Posts p ON p.Post_id = pt.Post_id
    WHERE pt.Tag_id IN (1,2,3)
    GROUP BY pt.Post_id
    HAVING COUNT(DISTINCT pt.Tag_id) = 3
    

提交回复
热议问题