An alternative to the accepted answer, probably faster:
SELECT p.*
FROM parent p JOIN join_table j ON p.id=j.parent_id
WHERE j.child_id=1 OR j.child_id=2
GROUP BY j.parent_id
HAVING COUNT(j.child_id)=2;
Question
Say I have 2 tables, called parent and child. A parent can have zero to many children, and a child can have 1 to many parents. How do I find all the parent elements that are parents of two specific children.
For instance, say I have Parents [p_a, p_b, p_c, p_d], and children: [c_a, c_b] They have a structure as follows:
How do I formulate a query to select p_c?
If they had a structure where p has [id, name] and c has [id, name] and there is a join_table with [parent_id, child_id]. (I have also given them sequential id's for this example to make things easier).
My attempt to solve it came up with the following SQL
SELECT p.*
FROM parent AS p
JOIN join_table AS j ON p.id = j.parent_id
JOIN children AS c ON j.child_id = c.id
WHERE c = 1
OR c = 2
But obviously this selects p_a and p_b as well as p_c. I've been looking at the UNION operator but can't seem to get it working.
Looking forward to your answers, thanks for reading. mike
EDIT: mentioned the id convention I'm using for the example
Solution 2
An alternative to the accepted answer, probably faster:
SELECT p.*
FROM parent p JOIN join_table j ON p.id=j.parent_id
WHERE j.child_id=1 OR j.child_id=2
GROUP BY j.parent_id
HAVING COUNT(j.child_id)=2;
OTHER TIPS
You are looking for parents where two specific child records exist. Use the EXISTS clause for that:
SELECT *
FROM parent p
WHERE EXISTS (select * from join_table j where j.parent_id = p.id and j.child_id = 1)
AND EXISTS (select * from join_table j where j.parent_id = p.id and j.child_id = 2);