一種選擇是使用排名變數,例如:
update player
join (select p.playerid,
@currank := @currank + 1 as rank
from player p
join (select @currank := 0) r
order by p.points desc
) ranks on (ranks.playerid = player.playerid)
set player.rank = ranks.rank;
join(select @currank:= 0)部分允許變數初始化而無需單獨的set命令.
測試用例:
create table player (
playerid int,
points int,
rank int
insert into player values (1, 150, null);
insert into player values (2, 100, null);
insert into player values (3, 250, null);
insert into player values (4, 200, null);
insert into player values (5, 175, null);
update player
join (select p.playerid,
@currank := @currank + 1 as rank
from player p
join (select @currank := 0) r
order by p.points desc
) ranks on (ranks.playerid = player.playerid)
set player.rank = ranks.rank;
結果:select * from player order by rank;
| playerid | points | rank |
| 3 | 250 | 1 |
| 4 | 200 | 2 |
| 5 | 175 | 3 |
| 1 | 150 | 4 |
| 2 | 100 | 5 |
5 rows in set (0.00 sec)
update player
join (select p.playerid,
if(@lastpoint <> p.points,
@currank := @currank + 1,
@currank) as rank,
@lastpoint := p.points
from player p
join (select @currank := 0, @lastpoint := 0) r
order by p.points desc
) ranks on (ranks.playerid = player.playerid)
set player.rank = ranks.rank;
對於測試用例,讓我們新增另乙個175分的玩家:
insert into player values (6, 175, null);
結果:select * from player order by rank;
| playerid | points | rank |
| 3 | 250 | 1 |
| 4 | 200 | 2 |
| 5 | 175 | 3 |
| 6 | 175 | 3 |
| 1 | 150 | 4 |
| 2 | 100 | 5 |
6 rows in set (0.00 sec)
如果你需要等級跳過乙個地方以防平局,你可以新增另乙個if條件:
update player
join (select p.playerid,
if(@lastpoint <> p.points,
@currank := @currank + 1,
@currank) as rank,
if(@lastpoint = p.points,
@currank := @currank + 1,
@currank),
@lastpoint := p.points
from player p
join (select @currank := 0, @lastpoint := 0) r
order by p.points desc
) ranks on (ranks.playerid = player.playerid)
set player.rank = ranks.rank;
結果:select * from player order by rank;
| playerid | points | rank |
| 3 | 250 | 1 |
| 4 | 200 | 2 |
| 5 | 175 | 3 |
| 6 | 175 | 3 |
| 1 | 150 | 5 |
| 2 | 100 | 6 |
6 rows in set (0.00 sec)
注意:請考慮我建議的查詢可以進一步簡化.
mysql 更新排名 MySQL更新排名和關係
我有下表 rank rankties teamname winningpercentage teama 1000 teamb 1000 teamc 500 teamd 250 teame 250 teamf 250 teamg 0 我想使用儲存的例程通過winningpercentage desc對...
mysql 分數排名,更新表
如何用mysql 查詢出資料出資料排名,然後加編號 表字段說明 查詢e task result表 score代表分數,task result id 代表id select rowno rowno 1 as rowno,task result id score from select task res...
Mysq遇到的問題整理更新
1 lock wait timeout exceeded try restarting transaction的問題解決 解決辦法 a 檢視當前的事務隔離級別 b 檢視當前資料庫的執行緒情況 c 沒有看到正在執行的很慢sql記錄執行緒,再去檢視innodb的事務表innodb trx,看下裡面是否有...