Reputation: 182
There is probably a simple answer to this but I can't seem to find it anywhere..
My table looks like this:
item_id tag_id
----------------------
100 55
101 55
100 320
102 320
100 77
100 489
101 200
Asking for items with tags 55 AND 320 should return item_id = 100 (but not 101 or 102 as they don't have both tags)
Upvotes: 1
Views: 44
Reputation: 413
You can try:
SELECT item_id
FROM table_name
WHERE tag_id IN (55,320)
GROUP BY item_id
HAVING COUNT(DISTINCT tag_id) > 1;
It will return item_id that have more than one distinct tag_id.
Pass your tags in IN by comma separated as many as you want.
Upvotes: 2
Reputation: 1329
SELECT item_id
FROM Table1
WHERE tag_id IN (55,320)
GROUP BY item_id
HAVING COUNT(DISTINCT tag_id) > 1
Upvotes: 0
Reputation: 175586
You could use HAVING
clause:
SELECT item_id
FROM tab_name
WHERE tag_id IN (1,2)
GROUP BY item_id
HAVING COUNT(DISTINCT tag_id) = 2;
or even:
SELECT item_id
FROM tab_name
GROUP BY item_id
HAVING GROUP_CONCAT(DISTINCT tag_id ORDER BY tag_id ) = '1,2';
Upvotes: 4