我有一个看起来像下面没有排名字段的表格。我想将该排名字段放在下表中。我如何在 MySQL 中实现它?
# name aa bb cc total | rank
1 name1 20 20 30 70 | 1
2 name2 10 20 30 60 | 2
3 name3 20 10 25 55 | 3
4 name4 20 20 30 70 | 1
5 name5 10 10 20 40 | 4
最佳答案
这里有一种方法,结果将根据总数排序。
mysql> create table test (id int, name varchar(100),total int);
Query OK, 0 rows affected (0.13 sec)
mysql> insert into test values
-> (1,'name1',70),
-> (2,'name2',60),
-> (3,'name3',55),
-> (4,'name4',70),
-> (5,'name5',40);
Query OK, 5 rows affected (0.02 sec)
select
id,
name,
case
when @cur_rank = total then @rank
else @rank := @rank + 1
end as rank,
@cur_rank := total as total
from test ,(select @rank:=0, @cur_rank:=0)r
order by total desc ;
+------+-------+------+-------+
| id | name | rank | total |
+------+-------+------+-------+
| 1 | name1 | 1 | 70 |
| 4 | name4 | 1 | 70 |
| 2 | name2 | 2 | 60 |
| 3 | name3 | 3 | 55 |
| 5 | name5 | 4 | 40 |
+------+-------+------+-------+
关于php - MySQL Rank 我的总分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28848108/