Skip to content
Advertisement

MySQL – Recursively list all parents and ancestors of all items in table

I have a table with a parent/child hierarchy that supports multiple (theoretically infinite) levels of nesting:

I am trying to build a query that produces a concatenated list of every item’s parent items up until the highest parent in the tree:

Based on a number of other answers here I have constructed the following MySQL query:

See Fiddle here: http://sqlfiddle.com/#!9/48d276f/902/0

But this query only works for one given child id (31 in this example). I did not succeed to expand this query for the whole table, is there some way to reset the counter variables at every next row in the table?

I have seen many answers that suggest using a fixed number of joins, but a solution that accepts a variable number of levels would be much more preferable.

In MySQL 8 this is possible thanks to recursive queries (thank you @GMB), but since we are still running on MySQL 5.7 I am interested if a solution exists for older versions as well.

Advertisement

Answer

If you are running MySQL 8.0, this is best solved with a recursive query:

Demo on DB Fiddle:

id | all_parents
-: | :----------
 1 | 0          
 2 | 0          
 3 | 0          
17 | 3,0        
31 | 17,3,0     
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement