Mysql: how to select groups having certain values?

后端 未结 6 674
遥遥无期
遥遥无期 2020-11-27 22:17

Say there is such table:

mysql> SELECT * FROM tags;
+---------+--------+
| post_id | tag_id |
+---------+--------+
|       1 |      2 |
|       1 |      3         


        
6条回答
  •  有刺的猬
    2020-11-27 22:54

    I've made some assumptions about your other tables. (i.e. that you have a table for posts that I have called posts and one with tag_id as the PK which I have called tag_table to avoid a nameclash with the posts/tags table that I can see you already call tags)

    You want posts where there does not exist a tag in the list {1,3} for which there does not exist a matching record with the corresponding post_id/tag_id so you can use a double NOT EXISTS construct as below.

    SELECT post_id
    FROM posts p
    WHERE NOT EXISTS 
        (SELECT * FROM tag_table tt
        WHERE tag_id IN (1,3)
        AND NOT EXISTS
            (SELECT * FROM tags t
            WHERE t.tag_id = tt.tag_id  and
            p.post_id = t.post_id)        
        )
    

    Another alternative approach is to use Group By and Count. A review of approaches to this problem is here.

提交回复
热议问题