You can use the INTERSECT -compound statement:
SELECT postid FROM post_category WHERE categoryid = 73 INTERSECT SELECT postid FROM post_category WHERE categoryid IN (130, 3, 4, 5)
This will select only those postid for which categoryid is 73 and at least one of categoryid = 130 , 3 , 4 or 5 .
This query is likely to run faster than an aggregate query ( GROUP BY ), since the sql server can use an index on categoryid (which you hope) to get a relevant postid , and then use a temporary index to calculate the intersection (by at least what sqlite does). If there is no postid with categoryid 73, then the second part of the request is never executed, since the intersection of an empty set with something else is always just empty.
To receive your messages, use the subquery:
SELECT post.* FROM post WHERE post.id IN (SELECT postid FROM post_category WHERE categoryid = 73 INTERSECT SELECT postid FROM post_category WHERE categoryid IN (130, 3, 4, 5))
Also note that you can add more INTERSECT components as you like.
source share