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子句).
我会尝试这样的事情:
SET @counter = 0; SELECT (@counter:=@counter+1)%3 as rr, grp, name FROM table ORDER by rr, grp
你可以做的是创建一个临时列,你在其中创建集合,给你这样的东西:
+-------+------+-----+ | 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 | +-------+------+-----+
要了解如何创建集合,请查看此问题/答案.
然后它很简单
ORDER BY tmp, group, name