我正在尝试通过几个不同的列对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 |
+------------+------------+------------+------------+
正如您所希望的那样,我希望通过订购和parent_id对项目进行排序。如果可能,我希望使用单个查询。如果这不可能,我可以将PHP循环与查询结合使用。如果可能的话,我想远离多个查询。
我需要一种排序方式,以便带有parent_id
的行(例如带id=5
的行)低于它的“父行”(带id=2
的行)。 'ordered'基于'level'。
我最接近的是通过以下方式对其进行排序:
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 |
+------------+------------+------------+------------+
答案 0 :(得分:3)
您是否尝试按Ordering和Parent_Id列的SUM
排序?假设这些都是数字数据类型,这应该有效:
SELECT *
FROM YourTable
ORDER BY Parent_Id + Ordering, Id
答案 1 :(得分:1)
SELECT * FROM mytable ORDER BY parent_id + ordering, id