MySQL查询优化

时间:2011-03-12 16:02:47

标签: php mysql optimization

所以我一直在研究一年的IRC游戏,用PHP编写并使用PHP到IRC框架。

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

得分合并部分(下面)的作品有意,但我想知道我是否可以优化这个过程,因为我觉得它很重(但想不出更好的东西):

$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

1 个答案:

答案 0 :(得分:0)

只有一个提示:毕竟使用此查询(如果您有适当的特权)

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

这会导致重新计算此表中的所有索引。您会注意到索引文件大小已更改为1kb(或几个字节)