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

前端 未结 2 1006
轮回少年
轮回少年 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:22

    Should be able to do this use NOT EXISTS, e.g.,

    select t1.post_id
    from post_tags as t1
        inner join post_tags as t2 on t2.post_id = t1.post_id
    where 
        t1.tag = 'clever' 
    and t2.tag = 'interesting' 
    and not exists (
        select *
        from post_tags t3
        where 
            t3.tag not in ('clever', 'interesting')
        and t3.post_id = t1.post_id
    )
    

提交回复
热议问题