I'm trying to sort a mysql table by a few different columns. Here's the table:
+------------+------------+------------+------------+
| id | parent_id | ordering | level |
+------------+------------+------------+------------+
| 1 | 0 | 0 | 0 |
+------------+------------+------------+------------+
| 2 | 0 | 2 | 0 |
+------------+------------+------------+------------+
| 3 | 0 | 3 | 0 |
+------------+------------+------------+------------+
| 4 | 0 | 4 | 0 |
+------------+------------+------------+------------+
| 5 | 2 | 0 | 1 |
+------------+------------+------------+------------+
| 6 | 0 | 1 | 0 |
+------------+------------+------------+------------+
And this is the result I'd like to achieve:
+------------+------------+------------+------------+
| id | parent_id | ordering | level |
+------------+------------+------------+------------+
| 1 | 0 | 0 | 0 |
+------------+------------+------------+------------+
| 6 | 0 | 1 | 0 |
+------------+------------+------------+------------+
| 2 | 0 | 2 | 0 |
+------------+------------+------------+------------+
| 5 | 2 | 0 | 1 |
+------------+------------+------------+------------+
| 3 | 0 | 3 | 0 |
+------------+------------+------------+------------+
| 4 | 0 | 4 | 0 |
+------------+------------+------------+------------+
As you can (hopefully) see, I would like to sort the items by ordering and parent_id. I would prefer, if possible, to use a single query. If this is not possible, I can use a PHP loop in combination with the query. I'd like to stay away from multiple queries if at all possible.
I need a way to sort so that a row with a parent_id such as row with id=5 is below it's "parent row" (row with id=2). 'ordering' is based on 'level'.
The closest I've come is by sorting this with:
SELECT * FROM table ORDER BY ordering,id,parent_id
Which returns:
+------------+------------+------------+------------+
| id | parent_id | ordering | level |
+------------+------------+------------+------------+
| 1 | 0 | 0 | 0 |
+------------+------------+------------+------------+
| 5 | 2 | 0 | 1 |
+------------+------------+------------+------------+
| 6 | 0 | 1 | 0 |
+------------+------------+------------+------------+
| 2 | 0 | 2 | 0 |
+------------+------------+------------+------------+
| 3 | 0 | 3 | 0 |
+------------+------------+------------+------------+
| 4 | 0 | 4 | 0 |
+------------+------------+------------+------------+
orderingnorparent_idare in a sorted order.