Update the rank in a MySQL Table

后端 未结 4 771
梦如初夏
梦如初夏 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:28

    EDIT: The update statement presented earlier did not work.

    Although this is not exactly what you are asking for: You can generate the rank on the fly when selecting:

    select p1.playerID, p1.points, (1 + (
        select count(playerID) 
          from Player p2 
         where p2.points > p1.points
        )) as rank
    from Player p1
    order by points desc
    

    EDIT: Trying the UPDATE statement once more. How about a temporary table:

    create temporary table PlayerRank
        as select p1.playerID, (1 + (select count(playerID) 
                                       from Player p2 
                                      where p2.points > p1.points
                  )) as rank
             from Player p1;
    
    update Player p set rank = (select rank from PlayerRank r 
                                 where r.playerID = p.playerID);
    
    drop table PlayerRank;
    

    Hope this helps.

提交回复
热议问题