Find leaf nodes in hierarchical tree
Your query didn't work because the sub-query includes NULL
. The following slight modification works for me:
SELECT * FROM `mytree` WHERE `id` NOT IN (
SELECT DISTINCT `parentid` FROM `mytree` WHERE `parentid` IS NOT NULL)
No clue why your query didn't work. Here's the identical thing in left outer join syntax - try it this way?
select a.*
from mytree a left outer join
mytree b on a.id = b.parentid
where b.parentid is null