MYSQL query only in set
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 wo开发者_Python百科uld 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:
SELECT entry_id
FROM yourtable
WHERE tag_id IN (1, 2)
GROUP BY entry_id
HAVING COUNT(*) = 2
An alternative approach that doesn't require uniqueness and can also be faster:
SELECT T1.entry_id
FROM yourtable T1
JOIN yourtable T2
ON T1.entry_id = T2.entry_id
AND T1.tag_id = 1
WHERE T2.tag_id = 2
SELECT entry_id
FROM tags t1 inner join tags t2
on (t1.entry_id = t2.entry_id and t1.tag_id = 1 and t2.tag_id = 2)
This is a good case for a self-join...
SELECT tagged1.entry_id
FROM tags tagged1
JOIN tags tagged2
ON tagged1.entry_id = tagged2.entry_id
AND tagged1.tag_id = 1
AND tagged2.tag_id = 2;
精彩评论