简体   繁体   English

我的SQL查询顺序,因此列中没有相同的值

[英]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 23

25 25

26 26

26 26

22 22

22 22

19 19

I want this result to be ordered like this so that no two values come consuctivley. 我希望将这种结果排序为这样,以便没有两个值可以使用。

23 23

25 25

26 26

22 22

26 26

22 22

19 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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