MySQL更新排名和关系

时间:2013-11-01 06:31:38

标签: mysql

我有下表:

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

我想使用存储的例程通过WinningPercentage DESC对它们进行排名,因此更新的表应该是:

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 个答案:

答案 0 :(得分:2)

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)