Mysql - How do I order results by alternating (1,2,3, 1, 2, 3, 1, 2, 3,) rows, is it possible?

后端 未结 5 1715
南旧
南旧 2020-12-10 20:48

I want to order my results by client 1, 2, 3, then again client 1, 2, 3, and so on.

Is there a way to do this without using a for loop or making three separate queri

5条回答
  •  萌比男神i
    2020-12-10 21:41

    Use:

    SELECT x.client_id, 
           x.project_id,
           x.project_name
      FROM (SELECT t.client_id,
                   t.project_id,
                   t.project_name,
                   CASE
                     WHEN @client_id != t.client_id THEN @rownum := 0
                     WHEN @client_id = t.client_id THEN @rownum := @rownum + 1
                     ELSE @rownum 
                   END AS rank,
                   @client_id := t.client_id
              FROM TABLE t,
                   (SELECT @rownum := 0, @client_id
          ORDER BY t.client_id) r) x
    ORDER BY x.rank, x.client_id
    

    MySQL doesn't have any ranking functionality, but luckily you can use variables. The key was resetting the @rownum value when the client_id doesn't match the previous client_id - the ORDER BY in the subquery is to ensure that clients are in order.

提交回复
热议问题