我有一个表格,每个团队都有这样的游戏分数:
id game_id game_rank score team_id
-------------------------------------------
5 1 0 15 1
4 1 0 25 2
1 1 0 40 3
3 1 0 40 4
2 1 0 55 5
7 2 0 0 1
6 2 0 0 2
我想按分数自动对队伍进行排序,并根据这些分数为他们分配游戏等级(第一名,第二名......)。我想允许基于重复分数的关系,并且只有在分数不同时才增加排名。
这是我想要的结果。
id game_id game_rank score team_id
-------------------------------------------
5 1 1 15 1
4 1 2 25 2
1 1 3 40 3
3 1 3 40 4
2 1 4 55 5
7 2 0 0 1
6 2 0 0 2
到目前为止,我有以下查询,但它不允许重复的游戏等级。
SET @lastscore = 0;
SET @ordering = 0;
UPDATE game_scores SET game_rank = (@ordering := @ordering + 1)
WHERE game_id = 1
ORDER BY score;
有人可以帮我处理重复的分数吗?
答案 0 :(得分:2)
SET @lastscore = 0;
SET @ordering = 0;
UPDATE game_scores
SET
game_rank = IF(score = @lastscore, @lastscore, (@ordering := @ordering + 1))
, score = (@lastscore := score)
WHERE game_id = 1
ORDER BY score;
您也可以在一个查询中执行此操作:
UPDATE game_scores
CROSS JOIN ( SELECT @lastscore:=0, @ordering:=0) AS parameter
SET
game_rank = IF(score = @lastscore, @lastscore, (@ordering := @ordering + 1))
, score = (@lastscore := score)
WHERE game_id = 1
ORDER BY score;
答案 1 :(得分:0)
每次得分与以前的分数不一致时你应该检查条件然后@ordering增加1个其他明智的@ordering与当前的@ordering相同
SET @lastscore := 0;
SET @ordering := 0;
UPDATE game_scores SET
IF(@lastscore = score, @ordering, @ordering := @ordering + 1),
game_rank = @ordering,
@lastscore := score
WHERE game_id = 1
ORDER BY score;