Mysql: how to select groups having certain values?

后端 未结 6 729
遥遥无期
遥遥无期 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:58

    If there aren't any unique constraints try:

    SELECT post_id 
    FROM tags 
    WHERE tag_id = 1 OR tag_id = 3 
    GROUP BY post_id 
    HAVING count(DISTINCT tag_id) = 2;
    

    Or use this HAVING clause, if trying to detect only two tag_id values:

    HAVING MIN(tag_id) <> MAX(tag_id)
    

    If post_id and tag_id both have an unique constraint, this should work too:

    SELECT post_id 
    FROM tags 
    WHERE tag_id = 1 OR tag_id = 3 
    GROUP BY post_id 
    HAVING count(*) = 2;
    

提交回复
热议问题