基本知识:
1.sql语句中,使用@来定义一个变量。如:@rank
2.sql语句中,使用:=来给变量赋值,:@rank:=123,则变量rank的值为123
3.sql语句中,if(A,B,C)表示,如果A条件成立,那么执行B,否则执行C,如:
4.@rank:= if(2>1,100,200)的结果是,rank的值为100。
行号
set @rownum:= 0;
select @rownum:=@rownum+1 as rownum,a.* from user_copy a;
行号
select score, @rk := @rk+1 as rank
from user_copy fans,(select @rk:=0) a order by score desc;
按分数排名
select class,score ,
if(@prerk = score,@rk,@rk:=@rk+1) as rank ,@prerk:=score
from user_copy ,(select @rk:=0,@prerk:=NULL) a order by score desc;
按课程 分数 排名 取第二名
select id,name,class,score from (
select id,name,class,score,
IF(@p=class,if(@prerk = score,@r,@r:=@r+1),@r:=1) AS rank, @p:=class ,@prerk:=score
from user_copy , (SELECT @p:=NULL,@prerk:=NULL,@r:=1) a order by class
) a where rank = 2 order by class;