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

后端 未结 2 553
无人共我
无人共我 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);
    

提交回复
热议问题