Home > Enterprise >  SQL find all items having a match for all items in another table
SQL find all items having a match for all items in another table

Time:10-16

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?

CodePudding user response:

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