概述
mysql到8.0之后就有rank和desc_rank函数了,但是在5.7没这玩意,想实现一个分组排名得靠自己手撸了.
分组排名
student
表就id/姓名/分数/班级几个字段,加上class
表就id/name两个字段。
需求是查询每个班级分数排名前三的所有人(不是3个人是所有人)
SELECT @last_class := st.class, CASE WHEN st.class = @last_class THEN CASE WHEN @score = st.score THEN @rank WHEN ( @score := st.score ) IS NOT NULL THEN @rank := @rank + 1 END ELSE @rank := 1 END rank, st.* FROM student st,( SELECT @score := NULL, @rank := 0, @last_class := NULL ) a ORDER BY st.class, st.score desc
结果
筛选
#EXPLAIN SELECT a.id AS studentId, NAME, a.class, a.score FROM ( SELECT @last_class := st.class, CASE WHEN st.class = @last_class THEN CASE WHEN @score = st.score THEN @rank WHEN ( @score := st.score ) IS NOT NULL THEN @rank := @rank + 1 END ELSE @rank := 1 END rank, st.* FROM student st,( SELECT @score := NULL, @rank := 0, @last_class := NULL ) aa ORDER BY st.class, st.score DESC ) a where a.rank
结果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。