As stated above, this is not recursive, but if you know how many steps you need to take the maximum, you can use something in these lines (perhaps using PHP to generate the query):
I would first set the parent id to NULL, not 0, but this is a personal preference.
SELECT * FROM table t1 LEFT JOIN table t2 ON t2.parent_id = t1.role_id LEFT JOIN table t3 ON t3.parent_id = t2.role_id WHERE t1.parent_id IS NULL
^^ No matter how deep you need to go in this case.
[ next bit is not strictly relevant ]
Then you can manipulate the output as follows:
SELECT (CASE WHEN (t1.name IS NULL AND t2.name IS NULL) THEN t3.name WHEN (t1.name IS NULL AND t2.name IS NOT NULL) THEN t2.name ELSE t1.name END) AS first, (CASE WHEN (t1.name IS NOT NULL AND t2.name IS NOT NULL) THEN t2.name WHEN (t2.name IS NULL AND t3.name IS NOT NULL) THEN NULL ELSE t3.name END) AS second, (CASE WHEN (t1.name IS NOT NULL) THEN t3.name ELSE NULL END) AS third FROM
Jon m
source share