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

前端 未结 3 682
旧巷少年郎
旧巷少年郎 2021-01-02 23:13

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:

         


        
相关标签:
3条回答
  • 2021-01-03 00:05

    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 |
    +------+------+--------------+
    
    0 讨论(0)
  • 2021-01-03 00:16

    I'd try something like:

    SET @counter = 0;
    SELECT (@counter:=@counter+1)%3 as rr, grp, name FROM table ORDER by rr, grp 
    
    0 讨论(0)
  • 2021-01-03 00:18

    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
    
    0 讨论(0)
提交回复
热议问题