Mysql: how to select groups having certain values?

htf picture htf · Jun 21, 2010 · Viewed 15.3k times · Source

Say there is such table:

mysql> SELECT * FROM tags;
+---------+--------+
| post_id | tag_id |
+---------+--------+
|       1 |      2 |
|       1 |      3 |
|       1 |      1 |
|       2 |      1 |
|       2 |      2 |
+---------+--------+
5 rows in set (0.00 sec)

Field names are pretty self-explanatory. I want to select post_ids that have both 1 and 3 tag_ids, so in this example it's only 1. I thought of something like SELECT post_id FROM tags GROUP BY post_id HAVING ... After having I'd like to list tag_ids that are present in this group. How do I do that?

Answer

rudi-moore picture rudi-moore · Jun 21, 2010

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;