MySQL排名次实现

参考来源

自然排名

实现结果:1,2,3,4,5;
思路实现:
设置名次自增变量,每次加1;

1
2
3
4
5
6
7
SELECT
obj.user_id,
obj.score,
@rownum := @rownum + 1 AS rownum
FROM
( SELECT user_id, score FROM `sql_rank` ORDER BY score DESC ) AS obj,
( SELECT @rownum := 0 ) r

同分同名逐次排名

实现结果:1,2,2,3,3;
思路实现:
设置两个变量,一个记录上一条记录的分数,一个记录名次;
与上一条记录的分数不同,名次自增;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
SELECT
obj.user_id,
obj.score,
CASE
WHEN @rowtotal = obj.score THEN
@rownum
WHEN @rowtotal := obj.score THEN
@rownum := @rownum + 1
WHEN @rowtotal = 0 THEN
@rownum := @rownum + 1
END AS rownum
FROM
( SELECT user_id, score FROM `sql_rank` ORDER BY score DESC ) AS obj,
( SELECT @rownum := 0, @rowtotal := NULL ) r

同分同名自然排名

实现结果:1,2,2,4,4;
思路实现:
设置三个变量,一个记录上一条记录的分数,一个记录名次,一个记录自然名次;
自然名次每次递增;
与上一条记录的分数相同,名次自增,不同则取值自然名次;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
SELECT
obj.user_id,
obj.score,
@rownum := @rownum + 1 AS num_tmp,
@incrnum :=
CASE
WHEN @rowtotal = obj.score THEN
@incrnum
WHEN @rowtotal := obj.score THEN
@rownum
END AS rownum
FROM
( SELECT user_id, score FROM `sql_rank` ORDER BY score DESC ) AS obj,
( SELECT @rownum := 0, @rowtotal := NULL, @incrnum := 0 ) r