示例:想要取出每个课程前3名的学生信息、课程id,成绩与对应课程内排名
创建student表:
s_id为学生id,s_name为学生姓名,s_sex为性别
创建score表:
s_id 为学生id,c_id为课程id,s_score为对应的成绩
#内嵌部分:
set @rank:=0;
select *, @rank:=case when @current_id<>c_id then 1 else @rank+1 end as rank,
@current_id:=c_id
from score
order by c_id, s_score desc;
此时的排序需要现基于课程id,再基于成绩逆序
#整体连起来写: set @rank:=0; select a.*, b.c_id, b.s_score, b.rank from(select *, @rank:=case when @current_id<>c_id then 1 else @rank+1 end as rank, @current_id:=c_id from score order by c_id,s_score desc)b left join student a on a.s_id=b.s_id having rank<=3 order by c_id, rank
注意:在最后的条件设定中需要用having不能用where,因为在原表中是不存在rank字段的,这是我们为了取数所构造的
发表评论