MySQL doesn’t support recursive queries so you have to do it the hard way:
- Select the rows where
ParentID = X
whereX
is your root. - Collect the
Id
values from (1). - Repeat (1) for each
Id
from (2). - Keep recursing by hand until you find all the leaf nodes.
If you know a maximum depth then you can join your table to itself (using LEFT OUTER JOINs) out to the maximum possible depth and then clean up the NULLs.
You could also change your tree representation to nested sets.