单个条件
SELECT
id,name,type,year,height,
IF
( @temp = type, @rank := @rank + 1, @rank := 1 ) ranking,
@temp := type
FROM
user,
(select @temp:= '', @rank:=0) t
ORDER BY
year,type,height DESC
多个条件
SELECT
id,name,type,year,height,
IF
( @temp = type AND @temp2 := year, @rank := @rank + 1, @rank := 1 ) ranking,
@temp := type,
@temp2 := year
FROM
user,
(select @temp:= '' ,@temp2:= '' , @rank:=0) t
ORDER BY
year,type,height DESC
经验分享
命名@的变量在同一个搜索中不能重名,比如上文中的@temp跟@temp2
@变量需要初始化,(select @temp:= ‘’ ,@temp2:= ‘’ , @rank:=0) t,如果不初始化会出现第一次执行时排序都为1的情况,执行第二次后对变量初始化后又能正常排序,这就是有些同学遇到这个问题的原因