Search code examples
mysqlhierarchical-dataadjacency-list

Mysql adjacency list ordering child after parent


I have a classic adjacency list for my menu structure. I use recursion to display them as an unordered list. But, in my admin area I want them to be display simply one after each other (in a HTML table structure). For that I only need on my MYSQL select to get them in the right order.

Parent 1
Child of parent 1
Child of parent 1
Parent 2
Child of parent 2
...

Right now I can't figure how to do that. My table contains "ID", "Parent_id", "Name", "Ordering" (the ordering column is set from 1 to X for every parent childs). Example :

id | Parent_id |    name     | ordering
---+-----------+-------------+---------
1  | 0         | Lorem       | 1
2  | 0         | Ipsum       | 2
3  | 1         | Dolor       | 2
4  | 0         | Amet        | 3
5  | 1         | Pract       | 1
6  | 2         | Maloc       | 1

Should give :

1  | 0         | Lorem       | 1
5  | 1         | Pract       | 1
3  | 1         | Dolor       | 2
2  | 0         | Ipsum       | 2
6  | 2         | Maloc       | 1
4  | 0         | Amet        | 3

Thanks for your advices

PS : I don't want to use a Nested Model as I can have a lot of update on the menu and don't want to break it.


Solution

  • As "a_horse_with_no_name" said it's impossible because MySQL doesn't support recursive. So I did it via PHP and recursion.

    The idea is to make a simple recursion and try to find childs from the current element. If it got some do an $tree = array_merge($tree, $childs) on it and continue the recursion.