2

我正在尝试按几个不同的列对 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     |
+------------+------------+------------+------------+
4

2 回答 2

3

您是否尝试按SUMOrdering 和 Parent_Id 列的排序?假设它们都是数字数据类型,这应该有效:

SELECT *
FROM YourTable
ORDER BY Parent_Id + Ordering, Id
于 2013-03-16T03:15:00.867 回答
1

SQLFiddle 演示

SELECT * FROM mytable ORDER BY parent_id + ordering, id
于 2013-03-16T03:23:51.143 回答