Update the rank in a MySQL Table

后端 未结 4 889
梦如初夏
梦如初夏 2020-12-08 06:14

I have the following table structure for a table Player

Table Player {  
Long playerID;  
Long points;  
Long rank;  
}

Assuming that th

4条回答
  •  广开言路
    2020-12-08 06:21

    Daniel, you have very nice solution. Except one point - the tie case. If tie happens between 3 players this update doesn't work properly. I changed your solution as following:

    UPDATE player  
        JOIN (SELECT p.playerID,  
                     IF(@lastPoint <> p.points,  
                        @curRank := @curRank + @nextrank,  
                        @curRank)  AS rank,  
                     IF(@lastPoint = p.points,  
                        @nextrank := @nextrank + 1,  
                        @nextrank := 1),  
                     @lastPoint := p.points  
                FROM player p  
                JOIN (SELECT @curRank := 0, @lastPoint := 0, @nextrank := 1) r  
               ORDER BY  p.points DESC  
              ) ranks ON (ranks.playerID = player.playerID)  
    SET player.rank = ranks.rank;
    

提交回复
热议问题