2011-03-12 52 views
0

所以我一直在研究IRC游戏一年,现在用PHP编写,并使用PHP到IRC框架。MySQL查询优化

最近,我添加了归档分数的功能(它们每隔几百次就会被重新设置),这迫使我更新各种管理功能。
我刚刚更新了一个函数,允许我合并两个玩家(一些用户不打扰他们的旧密码等等),以便合并归档分数(如果在我找到之前发生了重置重复账户)。

比分,融合部(下图)的作品已经打算,但我不知道是否是因为我觉得很沉重,我可以优化工艺(但想不出更好的东西):

$from_stats = $this->db->query("SELECT `games`, `wins`, `points`, `date_archive` FROM ".$this->dbprefix."score WHERE `id`=".$id1." AND `channel`='".$gamechan."' GROUP BY `date_archive`"); // get scores for the original account 
$to_stats = $this->db->query("SELECT `games`, `wins`, `points`, `date_archive` FROM ".$this->dbprefix."score WHERE `id`=".$id2." AND `channel`='".$gamechan."' GROUP BY `date_archive`"); // get scores for the duplicated account 
$from_games = array(); 
$from_wins = array(); 
$from_points = array(); 
$from_date = array(); 
while (list($fromstats_games,$fromstats_wins,$fromstats_points,$fromstats_date) = $this->db->fetchRow($from_stats)) { // build score arrays for the original account 
    $from_games[count($from_games)] = $fromstats_games; 
    $from_wins[count($from_wins)] = $fromstats_wins; 
    $from_points[count($from_points)] = $fromstats_points; 
    $from_date[count($from_date)] = $fromstats_date; 
} 
$to_games = array(); 
$to_wins = array(); 
$to_points = array(); 
$to_date = array(); 
while (list($tostats_games,$tostats_wins,$tostats_points,$tostats_date) = $this->db->fetchRow($to_stats)) { // build score arrays for the duplicated account 
    $to_games[count($to_games)] = $tostats_games; 
    $to_wins[count($to_wins)] = $tostats_wins; 
    $to_points[count($to_points)] = $tostats_points; 
    $to_date[count($to_date)] = $tostats_date; 
} 
foreach ($from_date as $key1 => $id1_date) { 
    foreach ($to_date as $key2 => $id2_date) { 
     if ($id1_date == $id2_date) { // merge scores if dates match 
      $from_games[$key1] += $to_games[$key2]; 
      $from_wins[$key1] += $to_wins[$key2]; 
      $from_points[$key1] += $to_points[$key2]; 
      $this->db->query("UPDATE ".$this->dbprefix."score SET `games`=".$from_games[$key1].", `wins`=".$from_wins[$key1].", `points`=".$from_points[$key1]." WHERE `id`=".$id1." AND `channel`='".$gamechan."' AND `date_archive`='".$id1_date."'"); 
      break; 
     } 
    } 
} 
$this->db->query("DELETE FROM ".$this->dbprefix."score WHERE `id`=".$id2); // delete all entries for the duplicated account 

回答

0

只是一个提示:毕竟使用此查询(如果你有合适的privilages)

$this->db->query("OPTIMIZE TABLE ".$this->dbprefix."score"); 

这应当引起所有索引此表被重新计算。你会注意到索引文件的大​​小已经改变为1kb(或几个字节)

+0

谢谢,会这样做:) – shroom 2011-03-12 16:14:57

+0

多一件事,而不是DELETE FROM考虑使用TRUNCATE TABLE - 如果没有触发器应该是执行,这是一种比DELETE更快的方式 – 2011-03-12 16:19:51

+0

是的,我在其他情况下使用它,但在这里我需要删除选定的条目。 感谢您的投入:) – shroom 2011-03-12 16:34:13