我正在尝试按几个不同的列对 mysql 表进行排序。这是表格:
+------------+------------+------------+------------+
| 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 |
+------------+------------+------------+------------+
这是我想要达到的结果:
+------------+------------+------------+------------+
| 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 |
+------------+------------+------------+------------+
如您所见(希望),我想通过 ordering 和 parent_id 对项目进行排序。如果可能的话,我更愿意使用单个查询。如果这不可能,我可以结合查询使用 PHP 循环。如果可能的话,我想远离多个查询。
我需要一种排序方法,以使带有parent_id
例如行的行id=5
位于其“父行”下方(带有 的行id=2
)。“排序”基于“级别”。
我最接近的是通过以下排序:
SELECT * FROM table ORDER BY ordering,id,parent_id
返回:
+------------+------------+------------+------------+
| 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 |
+------------+------------+------------+------------+