简体   繁体   中英

SQL find all items having a match for all items in another table

I have two tables:

Persons:

id,first_name,colorid
1,Mona,1
2,Davita,1
3,Mona,3
4,Davita,3
5,Marya,3
6,Mona,2
7,Whitby,3
8,Hardy,1
9,Hardy,2
10,Haskel,3

and colors table:

id,color
1,Green
2,Black
3,Red

I want to find first_names who have all the colors in the color table.

my attempt is:

SELECT DISTINCT P.first_name AS NAMES
FROM Persons P
JOIN Colors C ON C.id= P.colorid;

Is this correct?

select first_name 
from person 
group by first_name
having count(distinct colorid)  = (select count(*) from color)

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