I have a table that links entries with associated tags with the following data in it:
entry_id | tag_id
1 | 1
2 | 1
3 | 1
1 | 2
2 | 2
I am trying to write a query that returns only entries tagged with 1 AND 2, in this example entries 1 and 2 would be returned, while 3 would not, because it does not have both tags. The current query I am using works but I know can’t be right:
SELECT entry_id, GROUP_CONCAT(DISTINCT tag_id ORDER BY tag_id)
FROM tags
GROUP BY entry_id
HAVING GROUP_CONCAT(DISTINCT tag_id ORDER BY tag_id) LIKE "%1,2%";
If (entry_id, tag_id) is unique:
An alternative approach that doesn’t require uniqueness and can also be faster: