SQL(MySQL)中是否有办法在特定字段上执行“循环”ORDER BY?

时间:2009-03-10 16:56:12

标签: mysql sql-order-by

在SQL(MySQL)中是否有办法在特定字段上执行“循环”ORDER BY?

作为一个例子,我想拿一张像这样的表:

+-------+------+
| group | name |
+-------+------+
|     1 | A    |
|     1 | B    |
|     1 | C    |
|     2 | D    |
|     2 | E    |
|     2 | F    |
|     3 | G    |
|     3 | H    |
|     3 | I    |
+-------+------+

运行一个按此顺序生成结果的查询:

+-------+------+
| group | name |
+-------+------+
|     1 | A    |
|     2 | D    |
|     3 | G    |
|     1 | B    |
|     2 | E    |
|     3 | H    |
|     1 | C    |
|     2 | F    |
|     3 | I    |
+-------+------+

请注意,该表可能有很多行,因此我无法在应用程序中进行排序。 (我在查询中显然也有一个LIMIT子句。)

3 个答案:

答案 0 :(得分:7)

我会尝试类似的事情:

SET @counter = 0;
SELECT (@counter:=@counter+1)%3 as rr, grp, name FROM table ORDER by rr, grp 

答案 1 :(得分:5)

您可以做的是创建一个临时列,您可以在其中创建集合,为您提供以下内容:

+-------+------+-----+
| group | name | tmp |
+-------+------+-----+
|     1 | A    |   1 |
|     1 | B    |   2 |
|     1 | C    |   3 |
|     2 | D    |   1 |
|     2 | E    |   2 |
|     2 | F    |   3 |
|     3 | G    |   1 |
|     3 | H    |   2 |
|     3 | I    |   3 |
+-------+------+-----+

要了解如何创建集合,请查看此question/answer

然后是一个简单的

ORDER BY tmp, group, name

答案 2 :(得分:3)

您可以使用MySQL变量来执行此操作。

SELECT grp, name, @row:=@row+1 from table, (SELECT @row:=0) r ORDER BY (@row % 3);

+------+------+--------------+
| grp  | name | @row:=@row+1 |
+------+------+--------------+
|    1 | A    |            1 |
|    2 | D    |            4 |
|    3 | G    |            7 |
|    1 | B    |            2 |
|    2 | E    |            5 |
|    3 | H    |            8 |
|    1 | C    |            3 |
|    2 | F    |            6 |
|    3 | I    |            9 |
+------+------+--------------+