Need SQL Query to find Parent records without child records

前端 未结 6 1697
迷失自我
迷失自我 2020-12-08 10:12

I am not at all conversant in SQL so was hoping someone could help me with a query that will find all the records in a parent table for which there are no records in a child

相关标签:
6条回答
  • 2020-12-08 10:22

    You can use a NOT EXISTS clause for this

    SELECT ParentTable.ParentID
    FROM ParentTable
    WHERE NOT EXISTS (
        SELECT 1 FROM ChildTable
        WHERE ChildTable.ParentID = ParentTable.ParentID
    )
    

    There's also the old left join and check for null approach

    SELECT ParentTable.ParentID
    FROM ParentTable
    LEFT JOIN ChildTable
      ON ParentTable.ParentID = ChildTable.ParentID
    WHERE ChildTable.ChildID IS NULL
    

    Try both and see which one works better for you.

    0 讨论(0)
  • 2020-12-08 10:27

    With another example as

    Enumerate table

        id: SERIAL
        name: TEXT
        enumerate_id: INT
    

    All parents who have children (all branches of a tree, even roots, but no leaf!)

    SELECT id, name, enumerate_id
    FROM enumerate p
    WHERE EXISTS (
        SELECT 1 FROM enumerate c
        WHERE c.enumerate_id = p.id
    );
    

    All children who don't have children (all leafs of a tree)

    SELECT id, name, enumerate_id
    FROM enumerate p
    WHERE NOT EXISTS (
        SELECT 1 FROM enumerate c
        WHERE c.enumerate_id = p.id
    );
    

    Note that the only one who changes is the NOT EXISTS

    Hope it helps

    0 讨论(0)
  • 2020-12-08 10:33

    Outer join parent to child, and then having count(*) = 0.

    select
      p.parent_id,
      count(*)
    from
      parent p left outer join child c on p.parent_id = c.parent_id
    group by
      p.parent_id
    having
      count(*) = 0
    
    0 讨论(0)
  • 2020-12-08 10:46

    You can try NOT IN

    SELECT * FROM ParentTable WHERE ParentID NOT IN (SELECT DISTINCT ParentID FROM ChildTable)
    
    0 讨论(0)
  • 2020-12-08 10:49

    If you do a left join on the child table and simply say where the child parentID is null.

    SELECT ParentTable.ParentID FROM ParentTable P
        Left Join ChildTable C on C.ParentID = P.ParentID
        WHERE C.Id IS NULL;
    
    0 讨论(0)
  • 2020-12-08 10:49

    I simply dont understand whats the having clause doing in your query as I see already you are saying where ChildTable.ChildField_ = '2131' that already means you have record set for childfield 2131 Try the below query it would mean that if the parent doesnt have child in the Childtable with field 2131then o/p the same.

         SELECT    ParentTable.ParentID
             FROM      ParentTable 
             Where ParentTable.ParentID NOT IN (Select ChildID 
            From ChildTable where
             ChildTable.ChildField_ = '2131')
    
    0 讨论(0)
提交回复
热议问题