Skip to content
Advertisement

Mysql Mariadb recursive query

I have the following table :

and a recursive query on it :

which works and prints the following result :

I would have liked to add an extra column to the result, namely “parent_name”. How do I do this?

Edited to add: https://stackoverflow.com/a/22376973/2027239 That was the answer on an older question which I used to build my query

Advertisement

Answer

Use an inner join of tbl

✓

✓
id | name        | lvl | parentid | name      
-: | :---------- | --: | -------: | :---------
 3 | acateg 1.2  |   1 |        1 | categ 1   
 2 | xcateg 1.1  |   1 |        1 | categ 1   
 4 | categ 1.2.1 |   2 |        3 | acateg 1.2
 6 | categ 2.1   |   1 |        5 | categ 2   

db<>fiddle here

Or use left join to get all ids even those which have no parent.

✓

✓
id | name        | lvl | parentid | name      
-: | :---------- | --: | -------: | :---------
 1 | categ 1     |   0 |        0 | null      
 5 | categ 2     |   0 |        0 | null      
 3 | acateg 1.2  |   1 |        1 | categ 1   
 2 | xcateg 1.1  |   1 |        1 | categ 1   
 4 | categ 1.2.1 |   2 |        3 | acateg 1.2
 6 | categ 2.1   |   1 |        5 | categ 2   

db<>fiddle here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement