参考连接
建表语句如下:
CREATE TABLE `score_test` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`score` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
插入数据:
insert into `score_test`(`id`,`score`) values
(1,10.00),
(2,20.40),
(3,23.70),
(4,2.87),
(5,3.87),
(6,23.87),
(7,10.00),
(8,10.00);
1.最简单的排名,不考虑排名一样的情况。
SELECT
id,
score,
@rank := @rank+1
FROM
score_test,
(SELECT
@rank := 0) r ORDER BY score;
结果:
解析:此处使用了mysql的变量,每查一次,变量就加1,"(SELECT @rank := 0) r " 这里是把设置变量也当成一个表,相当于整个语句是查两张表。
2.考虑排名一样的情况,分数一样排名就一样,但是名次只递增,比如有2个第一名,那么再往下就是第二名而不是第三名。
SELECT
t.`id`,
t.`score`,
CASE
WHEN @preRank = t.score
THEN @curRank
WHEN @preRank := t.score
THEN @curRank := @curRank + 1
END AS rank
FROM
score_test t,
(SELECT
@curRank := 0,@preRank = NULL) r
ORDER BY t.`score`;
解析: "WHEN @preRank := t.score" 经本人测试,这里会返回 true。
3.考虑排名一样的情况,分数一样排名就一样,但是名次跳级,比如有2个第一名,那么再往下就是第3名而不是第2名。
SELECT
id,
score,
rank
FROM
(SELECT
id,
score,
@curRank := IF(
@prevRank = score,
@curRank,
@incRank
) AS rank,
@incRank := @incRank + 1,
@prevRank := score
FROM
score_test,
(SELECT
@curRank := 0,
@prevRank := NULL,
@incRank := 1) r
ORDER BY score) s