MySQL两个列的排序混合togather

时间:2017-12-06 13:24:42

标签: mysql sql

我有这张桌子

id   |    TOP    |    POS
1    |    60     |    1
2    |    50     |    2
3    |    40     |    3
4    |    30     |    4
5    |    20     |    5
6    |    10     |    6

我需要这样的结果:

id   |    TOP    |    POS
1    |    60     |    1
6    |    10     |    6
2    |    50     |    2
5    |    20     |    5
3    |    40     |    3
4    |    30     |    4

基本上我需要TOP列DESC的订单结果,但每行之间按POS DESC列的顺序放置结果。

我尝试使用MOD但结果错了

SELECT * FROM (
select 
    @row := @row + 1 as row,
    a.*
from table a
order by TOP desc
) t ORDER BY IF(MOD(row, 2) = 1, TOP, POS);

1 个答案:

答案 0 :(得分:0)

为了做你想做的事,你需要两个排序键:TOP排序的行和POS排序的行。这意味着您必须加入两个查询。

然后首先按这两个键中的较小者排序(TOP60 / POS1的行#1为TOP,TOP10 / POS6的行为#1为POS,所以这两个为第一个),然后由TOP键(所以TOP60) / POS1优先于TOP10 / POS6)。

select a1.*
from
(
  select 
    @rowtop := @rowtop + 1 as row,
    a.*
  from mytable a
  cross join (select @rowtop := 0) vars
  order by top desc
) a1 
join
(
  select 
    @rowpos := @rowpos + 1 as row,
    a.*
  from mytable a
  cross join (select @rowpos := 0) vars
  order by pos desc
) a2 using(id)
order by least(a1.row, a2.row), a1.row;

REXTESTER DEMO:http://rextester.com/ZKOL97078