Consider this table ‘cat_post’:
entry_id cat_id
2 2
2 4
2 76
3 2
3 4
3 76
4 2
4 76
I need to select the entries that have both a row with cat_id = 2 and one with cat_id = 4 (not all entries that have either 2 or 4), so this select:
select * from cat_post where cat_id IN (2,4)
will produce:
entry_id cat_id
2 2
2 4
3 2
3 4
4 2
Which is not what I want. I need to get entries if they have both a row with 2 and one with 4, but not 2 or 4, like:
entry_id cat_id
2 2
2 4
3 2
3 4
(without entry_id 4 in this case)
What query can I use to get this result?
You could use something like:
This is extensible to more than two values in your “in” set, but will fail if
(entry_id,cat_id)is not a unique key. If that’s not the case, use:Example: