views:

44

answers:

2

I have a table that has id, name, level (the depth) and parrent_id, is there any nice way to remove all nodes without any children? (On one level suffices)? I know I can do it in application - load all the nodes on given level and the check if they have children, if not remove, but this whould probably be more effective in SQL and I'm not SQL guru :)

+2  A: 
SELECT * FROM mytable where id in (SELECT parent_id from mytable)

This should do the job

anthares
+2  A: 

You could try

SELECT  DISTINCT tParent.*
FROM    Table tParent LEFT JOIN
        Table tChild ON tParent.ID = tChild.ParentID
WHERE   tChild.ID IS NOT NULL

Even better would be to try

SELECT  *
FROM    Table t
WHERE   NOT EXISTS(SELECT 1 FROM Table WHERE ParentID = t.ID)
astander
The question is to remove those that have no childrens
anthares
OK, sorry, I see what you meen. Should change to *IS NOT NULL*
astander
Exactly, I got it wrong the first time, too :)
anthares
thanks the second one did the trick, I used however NOT EXISTS (for all parrents without children)
kane77
OK, I fixed it up.
astander