基于多列排序MySql

时间:2013-03-16 03:11:17

标签: php mysql

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

2 个答案:

答案 0 :(得分:3)

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

SELECT *
FROM YourTable
ORDER BY Parent_Id + Ordering, Id

答案 1 :(得分:1)

SQLFiddle Demo

SELECT * FROM mytable ORDER BY parent_id + ordering, id