为什么内部ORDER BY不起作用?

时间:2015-10-16 17:51:09

标签: mysql sql-order-by

以下是我的查询结构:

(select @rnk := @rnk + 2 `rank` ,* from table1, (select @rnk := -1) x order by col1)
union all
(select @rnk2 := @rnk2 + 2 `rank`,* from table2, (select @rnk2 := 0) x)
order by rank limit 10

根据结果,我认为order by col1不起作用。为什么呢?

我想要的是:首先,select先按order by col1排序,然后按order by rant替换最终结果。怎么办?

修改:想象一下这个结果:

select @rnk := @rnk + 2 `rank` ,* from table1, (select @rnk := -1) x order by col1

// output: blut, green, red


select @rnk2 := @rnk2 + 2 `rank`,* from table2, (select @rnk2 := 0) x

// output: five, three, one, six, seven, two

现在我想要输出

的订单
blue, five, green, three, red, one, six, seven, two

但是上面的查询并不像那样。为什么呢?

1 个答案:

答案 0 :(得分:3)

order by col1放在另一级子查询中:

(SELECT @rnk := @rnk + 2 as rank, t.*
 FROM (SELECT * FROM table1 ORDER BY col1) AS t
 CROSS JOIN (SELECT @rnk := -1) AS x)
UNION ALL
(SELECT @rnk2 := @rnk2 + 2 AS rank, *
 FROM table2
 CROSS JOIN (SELECT @rnk2 := 0) AS x)
ORDER BY rank

有时在您分配rank列的同一查询中进行排序有效,但不能保证,所以最好在子查询中进行。