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?
If there aren’t any unique constraints try:
Or use this
HAVINGclause, if trying to detect only twotag_idvalues:If post_id and tag_id both have an unique constraint, this should work too: