我有一张叫做竞赛的桌子:
+-------+-------+------+
| name | Points | Rank |
+-------+-------+------+
| Stud1 | 50 | 0 |
| Stud2 | 40 | 0 |
| Stud3 | 20 | 0 |
| Stud4 | 20 | 0 |
| Stud5 | 15 | 0 |
| Stud6 | 10 | 0 |
+-------+-------+------+
点数列将继续使用点进行更新,并根据点数生成等级。
请帮我这样做。
答案 0 :(得分:1)
不要存储排名。只需动态计算......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(name VARCHAR(12) PRIMARY KEY,points INT NOT NULL);
INSERT INTO my_table VALUES
('Stud1',50),
('Stud2',40),
('Stud3',20),
('Stud4',20),
('Stud5',15),
('Stud6',10);
解决方案1:
SELECT x.*
, FIND_IN_SET(points,(SELECT GROUP_CONCAT(DISTINCT points ORDER BY points DESC) FROM my_table)) n
FROM my_table x;
+-------+--------+------+
| name | points | n |
+-------+--------+------+
| Stud1 | 50 | 1 |
| Stud2 | 40 | 2 |
| Stud3 | 20 | 3 |
| Stud4 | 20 | 3 |
| Stud5 | 15 | 4 |
| Stud6 | 10 | 5 |
+-------+--------+------+
解决方案2:
SELECT x.*
, CASE WHEN @prev = points THEN @i:=@i ELSE @i:=@i+1 END rank
, @prev := points FROM my_table x
, (SELECT @prev:=null,@i:=0) vars
ORDER
BY points
, name;
+-------+--------+------+-----------------+
| name | points | rank | @prev := points |
+-------+--------+------+-----------------+
| Stud6 | 10 | 1 | 10 |
| Stud5 | 15 | 2 | 15 |
| Stud3 | 20 | 3 | 20 |
| Stud4 | 20 | 3 | 20 |
| Stud2 | 40 | 4 | 40 |
| Stud1 | 50 | 5 | 50 |
+-------+--------+------+-----------------+