How do I structure a SQL query to find an object that is the parent of two specific other objects?

故事扮演 提交于 2019-12-04 05:28:34

问题


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:

  • p_a has c_a as a child
  • p_b has c_b as a child
  • p_c has both c_a and c_b as children
  • p_d has no children

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


回答1:


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;



回答2:


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);


来源:https://stackoverflow.com/questions/23126518/how-do-i-structure-a-sql-query-to-find-an-object-that-is-the-parent-of-two-speci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!