Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 285
user60858 Avatar asked Mar 10 '09 16:03

user60858


People also ask

Does MySQL use index for order by?

Use of Indexes to Satisfy ORDER BY. In some cases, MySQL may use an index to satisfy an ORDER BY clause and avoid the extra sorting involved in performing a filesort operation.

What is using filesort in MySQL?

In MySQL, filesort is the catch-all algorithm for producing sorted results for ORDER-BY or GROUP-BY queries. MySQL has two algorithms for filesort, both the original and the modified algorithms are described in the user manual.

How do I sort a MySQL query?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


2 Answers

I'd try something like:

SET @counter = 0;
SELECT (@counter:=@counter+1)%3 as rr, grp, name FROM table ORDER by rr, grp 
like image 87
vartec Avatar answered Nov 14 '22 23:11

vartec


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
like image 22
achinda99 Avatar answered Nov 14 '22 22:11

achinda99