在mysql数据库中高效更新数据

时间:2013-01-11 07:01:54

标签: php mysql optimization

现在我想创建一个游戏的排名系统,假设目前的排名如下:

player  rank        
A       : 1 
B       : 2     
C       : 3 
D       : 4 
E       : 5 

在玩家D在比赛中击败玩家B之后,等级将如下改变:

player  rank        
A       :  1    
D       :  2    
B       :  3    
C       :  4    
E       :  5    

我怎样才能在mysql数据库中高效更新数据?

1 个答案:

答案 0 :(得分:1)

我不是存储过程的专家,但我认为如果你创建一个带有参数“player1”和“player2”的存储过程,其中player1是排名较高的玩家,那么这样的东西可能有效:

# Get current player ranks
SET @player1rank = (SELECT `Rank` FROM `RankTable` WHERE `Player` = player1);
SET @player2rank = (SELECT `Rank` FROM `RankTable` WHERE `Player` = player2);
# Drop ranks for player 1 down to player 2
UPDATE `RankTable` SET `Rank` = `Rank`+1 WHERE `Rank` >= @player1rank AND `Rank` < @player2rank;
# Now update player2's rank
UPDATE `RankTable` SET `Rank` = @player1rank WHERE `Player` = player2;

作为一个存储过程,这将运行得非常快 - 如果您的表变大,这是一个额外的优势。

这是我的尝试,它没有在MySQL 4.0中使用PhpMyAdmin注册(找不到版本),但它可以在MySQL 5+上运行,希望能让你朝着正确的方向前进......

DELIMITER $$
CREATE PROCEDURE rerank_players (IN player1 VARCHAR (100), IN player2 VARCHAR (100))
BEGIN
   DECLARE player1rank, player2rank INT;
   SET player1rank = (SELECT Rank FROM RankTable WHERE Player = player1);
   SET player2rank = (SELECT Rank FROM RankTable WHERE Player = player2);
   UPDATE RankTable SET Rank = Rank+1 WHERE Rank >= player1rank AND Rank < player2rank;
   UPDATE RankTable SET Rank = player1rank WHERE Player = player2;
END
$$

您需要将参数声明中VARCHAR的长度调整为数据长度,并重命名表格和领域等...