Connect By Prior Equivalent for MySQL

MySQL doesn’t support recursive queries so you have to do it the hard way:

  1. Select the rows where ParentID = X where X is your root.
  2. Collect the Id values from (1).
  3. Repeat (1) for each Id from (2).
  4. 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.

Leave a Comment