简体   繁体   中英

My SQL query order so that no same value from the column come together

I m fetching data from multiple tables and want to sort the result so that no two values come together.

for example query returns the following data.

23

25

26

26

22

22

19

I want this result to be ordered like this so that no two values come consuctivley.

23

25

26

22

26

22

19

You actually cannot guarantee that no two values come together (for instance, all values might be the same). But you can distribute them. Here is a method using a subquery and variables:

select t.*
from (select q.*,
             (@rn := if(@v = col, @rn + 1,
                        if(@v := col, 1, 1)
                       )
             ) as rn
      from (query) q cross join
           (select @v := -1, @rn := 0) vars
      order by col
     ) t
order by rn, col;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM