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

后端 未结 2 550
无人共我
无人共我 2021-01-27 01:37

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 par

相关标签:
2条回答
  • 2021-01-27 01:45

    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);
    
    0 讨论(0)
  • 2021-01-27 01:53

    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;
    
    0 讨论(0)
提交回复
热议问题