mysql查询⽣成⾃增排序
mysql 查询⽣成⾃增排序,以及union all的⼦查询乱序问题
今天做sql语句练习50题(Mysql版) 时,第19题:按各科成绩进⾏排序,并显⽰排名时。需要将三个科⽬的分数按照从⾼到低排序,并且设置排列序号。⼤致思路就是将三个科⽬分别排序并⽣成个各⾃的序号,再⽤union all并表。
⽣成序号
buffer cache区别⾸先,使⽤如下⽅法⽣成⼀列单元格,@row:=0将0赋值给@row,并⽤@row:=@row+1实现序号的⾃增效果。
select @row1 := @row1 +1 from (select @row1 := 0) r
union all乱序问题
加⼊上⾯的序号代码后,写了如下的查询语句。但是发现结果的顺序并不是像⼦查询中我排序的集成结果,顺序完全打乱。
SELECT * from
(select a.*,@row1 := @row1 +1 from score a,
(select @row1 := 0) r
where c_id='01'
order by s_score desc)a
UNION all
(select a.*,@row2 := @row2 +1 from score a,
(select @row2 := 0) r
where c_id='02'
order by s_score desc)
UNION all
(select a.*,@row3 := @row3 +1 from score a,
(select @row3 := 0) r
syntax error near voidwhere c_id='03'
order by s_score desc) ;
局部变量表结果如下:
结果中c_id 为02和03课程的分数排序已经乱了。整个表格的排序是按照c_id,s_id升序来排列的,从⽹上搜索也得知,union all的优先级会⽐order by⾼,⽽union all会优先按照表的主键默认来排序。
通过测试和度娘,将⼦查询再次内嵌,如下:
SELECT * from
(select a.*,@row1 := @row1 +1 from score a, (select @row1 := 0) r
where c_id='01'
order by s_score desc)a
UNION all
select b.* from
(select a.*,@row2 := @row2 +1 from score a, (select @row2 := 0) r
微软开放了xp的源代码where c_id='02'
order by s_score desc) b
UNION all
select c.* from
(select a.*,@row3 := @row3 +1 from score a, (select @row3 := 0) r
mysql语句顺序where c_id='03'
order by s_score desc) c;
最终的查询结果是正确的了。
用mysql录入大量数据
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论