2013-11-01 58 views
3

我有如下表:MySQL的更新排名和紐帶

Rank RankTies TeamName WinningPercentage 
       TeamA  1000 
       TeamB  1000 
       TeamC  500 
       TeamD  250 
       TeamE  250 
       TeamF  250 
       TeamG  0 

我想用一個存儲程序通過WinningPercentage降序排列這些使更新後的表應該是:

Rank RankTies TeamName WinningPercentage 
1  2   TeamA  1000 
1  2   TeamB  1000 
3  1   TeamC  500 
4  3   TeamD  250 
4  3   TeamE  250 
4  3   TeamF  250 
7  1   TeamG  0 

我可以使用臨時表來做到這一點,但有沒有更優雅的解決方案,如一個UPDATE語句?

回答

1

SQLFiddle demo

(select * from T) T2這裏,以避免在您不能使用子查詢更新表MySQL的限制:("You can't specify target table 'T' for update in FROM clause"

update T T1 set RankTies=(select count(*) from 
          (select * from T) T2 
          where T2.WinningPercentage=T1.WinningPercentage), 

Rank=(select count(*)+1 from 
          (select * from T) T2 
          where T2.WinningPercentage>T1.WinningPercentage) 
+0

哇!這非常簡單和優雅。謝謝。 – user1822391