Need SQL Query to find Parent records without child records

前端 未结 6 1729
迷失自我
迷失自我 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.

提交回复
热议问题