以下是我的查询结构:
(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
但是上面的查询并不像那样。为什么呢?
答案 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
列的同一查询中进行排序有效,但不能保证,所以最好在子查询中进行。