I assume you want one form of query that can be used to answer all three questions, not a different kind of query for each question.
These solutions take advantage of COUNT()
not counting NULL
s. When the OUTER JOIN
does not match a row in t2
, it results in NULL
for all columns from t2
.
get ID 10, if I try to find (A,B,C)
ID 10 has three distinct term values, and we're searching for all three.
SELECT t1.ID
FROM TableA t1 LEFT OUTER JOIN TableA t2
ON (t1.ID = t2.ID AND t1.term = t2.term AND t2.term IN ('A', 'B', 'C'))
GROUP BY t1.ID
HAVING COUNT(t1.term) = COUNT(t2.term);
get NOTHING if I try to find (A,B)
Both ID 10 and ID 20 have three distinct term values, but our search is only for two. The counts are 3 = 2 for both IDs, so neither have equal counts.
SELECT t1.ID
FROM TableA t1 LEFT OUTER JOIN TableA t2
ON (t1.ID = t2.ID AND t1.term = t2.term AND t2.term IN ('A', 'B'))
GROUP BY t1.ID
HAVING COUNT(t1.term) = COUNT(t2.term);
get ID 20, if I try to find NOT in (C,D)
ID 20 has three distinct term values, and all three of them are NOT 'C' or 'D'. So the counts are equal.
SELECT t1.ID
FROM TableA t1 LEFT OUTER JOIN TableA t2
ON (t1.ID = t2.ID AND t1.term = t2.term AND t2.term NOT IN ('C', 'D'))
GROUP BY t1.ID
HAVING COUNT(t1.term) = COUNT(t2.term);