Need SQL Query to find Parent records without child records

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

提交回复
热议问题