I have a cross-reference table:
ID | tag
1 | 4
1 | 5
1 | 6
2 | 4
2 | 5
2 | 8
3 | 2
I need to select the IDs that match all of a
The idea of the query is that you need to match the number of records to the number of values you have provided in the WHERE
clause.
SELECT ID
FROM tableName
WHERE tag IN (4, 8)
GROUP BY ID
HAVING COUNT(*) = 2
if unique constraint was not specified on tag for every ID, then DISTINCT
is needed
SELECT ID
FROM tableName
WHERE tag IN (4, 8)
GROUP BY ID
HAVING COUNT(DISTINCT tag) = 2