Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for a particular scenario

Tags:

sql

Considering the sample table below:

Profile_ID  Child_ID

1           1
1           2
1           3

2           1
2           2

3           1
3           2
3           3
3           5

I want to construct an SQL query which gives me the profile IDs which are applicable to children 1 AND 2 AND 3... this implies that profile_ID 2 will not be in the result as profile 2 is only applied to children 1 and 2.. but I expect that profile 3 is included.

My idea is something similar to this

SELECT Profile_ID
FROM table
WHERE Child_ID IN (1 AND 2 AND 3)

Now, I am well aware that IN serves as an OR function... Is there a similar way to achieve similar functionality to the IN clause with an AND rather than an OR?

Thanks in advance for all your help.

like image 600
jaja Avatar asked Apr 29 '12 18:04

jaja


1 Answers

Try this:

select profile_id from t
where child_id in (1, 2 ,3)
group by profile_id
having count(distinct child_id) = 3

Here is the fiddle to play with.

NOTE: Make sure 3 matches the amount of items in the in clause.

like image 129
Mosty Mostacho Avatar answered Sep 18 '22 12:09

Mosty Mostacho