簡體   English   中英

MySQL查詢優化

[英]MySQL queries optimization

因此,我從事IRC游戲已經一年了,它是用PHP編寫並使用PHP to 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

提示:畢竟使用此查詢(如果您具有適當的特權)

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

這將導致重新計算該表中的所有索引。 您會注意到索引文件的大​​小已更改為1kb(或幾個字節)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM