Query to find posts with an exact set of tags (many-to-many relationship)

前端 未结 2 1011
轮回少年
轮回少年 2021-01-21 14:32

Suppose I have the following three tables expressing a relationship where posts are given tags (a many-to-many relationship):

create table posts (id integer, con         


        
2条回答
  •  情书的邮戳
    2021-01-21 15:24

    This is an exact relational division problem.

    In SQL Server a well performing method (assuming unique constraint on post_id,tag) is

    SELECT post_id
    FROM   post_tags
    GROUP  BY post_id
    HAVING MIN(CASE
                 WHEN Keyword IN ( 'clever', 'interesting' ) THEN 1
                 ELSE 0
               END) = 1
           AND SUM(CASE
                     WHEN Keyword IN ( 'clever', 'interesting' ) THEN 1
                     ELSE 0
                   END) = 2  
    

    So I wouldn't rule out the idea of using GROUP_CONCAT in the HAVING instead.

    HAVING GROUP_CONCAT(DISTINCT Keyword ORDER BY Keyword) = 'clever,interesting'
    

提交回复
热议问题