Select parent if all children meet criteria

前端 未结 3 1964
小蘑菇
小蘑菇 2021-02-14 14:29

I have tables set up like so:

Parent
------
id, ...

Child
-----
id, parent_id, x, y

I want to find the Parents, or the distinct parent_id(s),

相关标签:
3条回答
  • 2021-02-14 15:12

    You can use NOT EXISTS

    SELECT id 
    FROM Parent p
    WHERE NOT EXISTS
    (
       SELECT 1 FROM Child c
       WHERE c.parent_Id = p.id
       AND c.x <> c.y
    )
    

    Edit: Here's the sql-fiddle: http://sqlfiddle.com/#!3/20128/1/0

    0 讨论(0)
  • 2021-02-14 15:14

    This is what you need?

      select id from parent where id not in(
        select parent_id from chile 
        where x<>y
        group by parent_id)
    
    0 讨论(0)
  • 2021-02-14 15:17

    Should join 2 tables first because the parents does not have children that will satisfy

    And should add index for pa_id column

    SELECT DISTINCT pa.id 
    FROM pa INNER JOIN c ON c.pa_id = pa.id 
    WHERE NOT EXISTS ( SELECT 1 FROM c WHERE c.parent_Id = p.id and c.x <> c.y )
    
    0 讨论(0)
提交回复
热议问题