tags:

views:

522

answers:

3

Is there a way in SQL (MySQL) to do a "round robin" ORDER BY on a particular field?

As an example, I would like to take a table such as this one:

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

And run a query that produces results in this order:

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

Note that the table may have many rows, so I can't do the ordering in the application. (I'd obviously have a LIMIT clause as well in the query).

+4  A: 

What you can do is create a temporary column in which you create sets to give you something like this:

+-------+------+-----+
| 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 |
+-------+------+-----+

To learn how to create the sets, have a look at this question/answer.

Then its a simple

ORDER BY tmp, group, name
achinda99
+6  A: 

I'd try something like:

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

You can use MySQL variables to do this.

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 |
+------+------+--------------+
rjh