Consider this demo:
CREATE TEMP TABLE table1(id int, value int); INSERT INTO table1 VALUES (1,111),(1,112),(1,113) ,(2,111),(2,112),(2,116) ,(3,111),(3,122),(3,123) ,(4,126) ,(5,123),(5,125) ,(6,111),(6,112),(6,116); CREATE TEMP TABLE table2(value int); INSERT INTO table2 VALUES (111) ,(112) ,(116); SELECT t1.id FROM table1 t1 JOIN table2 t2 USING (value) GROUP BY t1.id HAVING count(*) = (SELECT count(*) FROM table2) ORDER BY t1.id;
Result:
id ----- 2 6
Returns all the identifiers table1
that appear with all the values ββprovided by table2
once.
Works for any number of rows in both tables.
If duplicate rows appear in table1
, do this:
HAVING count(DISTINCT value) = (SELECT count(*) FROM table2)