mysql排序同值排名一致。
假设Scores表数据:
+----+-------+ | Id | Score | +----+-------+ | 1 | 3.50 | | 2 | 3.65 | | 3 | 4.00 | | 4 | 3.85 | | 5 | 4.00 | | 6 | 3.65 | +----+-------+根据分数排名,同样分数排名一致,期望结果:
+-------+------+ | Score | Rank | +-------+------+ | 4.00 | 1 | | 4.00 | 1 | | 3.85 | 2 | | 3.65 | 3 | | 3.65 | 3 | | 3.50 | 4 | +-------+------+实现所用到的只是点:
1.mysql用户自定义变量--@
2.if函数
实现语句:
SELECT
IF (
@current_score = A.Score ,@current_rank ,@current_rank :=@current_rank + 1
) AS rank ,@current_score := A.Score,
A.*
FROM
(
SELECT
Score
FROM
Scores
ORDER BY
Score DESC
) A,
(
SELECT
@current_score := NULL ,@current_rank := 0
) B