简体   繁体   中英

How to find all rows that have all another column values

I have two tables like these:

Tb1
------------
col
1
2
3

Tb2
-----------
id name Tb1_col
1   a    1
2   a    2
3   b    1
4   a    3

Now I want to fetch all name values from Tb2 that have all col values from Tb1 . For this example I just expect a .

One way to do this is to JOIN Tb2 to Tb1 on Tb1_col and check that the number of distinct values for a given name is the same as the number of rows in Tb1 :

SELECT Tb2.name
FROM Tb2
JOIN Tb1 ON Tb1.col = Tb2.Tb1_col
GROUP BY Tb2.name
HAVING COUNT(DISTINCT Tb2.Tb1_col) = (SELECT COUNT(*) FROM Tb1)

Output

a

Demo on dbfiddle

Not very elegant solution, but....

SELECT distinct name from Tb2 as t1
WHERE NOT EXISTS (SELECT t2.col, t3.id
                  FROM Tb1 as t2 LEFT JOIN Tb2 as t3 ON t3.Tb1_col = t2.col
                                                     AND t3.name = t1.name
                  WHERE t3.id IS NULL);

If tb1_col is defined as a foreign key (meaning that all values are valid references), then Nick's answer can be simplified:

SELECT Tb2.name
FROM Tb2
GROUP BY Tb2.name
HAVING COUNT(DISTINCT Tb2.Tb1_col) = (SELECT COUNT(*) FROM Tb1)

If tb1_col never duplicates for a given name, then using:

HAVING COUNT(*) = (SELECT COUNT(*) FROM Tb1)

should be even more efficient.

A simple left join should do it?

select tb1.id, tb2.id, tb2.name
from tb1
Left join tb2 on tb1.id = tb2.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM