Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

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

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 queries? Not only that, but I am working with paginated data so it needs to return x results, but consistently.

Any ideas? GROUP BY maybe?

client_id  project_id  project_name  
---------- ----------  ------------
 1         42          project abc
 2         49          project xyz
 3         41          project 123
 1         22          project apple
 2         29          project orange
 3         21          project banana
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...