改善脚本执行时间

时间:2015-07-07 19:52:24

标签: php mysql

我想改进插入查询的执行时间,因为我的webhost不会更改max_execution_time。下面的脚本包含对wallclock执行时间的测试。这导致22秒的执行时间太长,因为webhost将默认值保持为30秒。在下面的代码之后,需要执行更多代码。作为参考,tblPlayers中约有1000名玩家。

$time_start = microtime(true);

$sqlTotalPoints = array();
$sqlCompetingPlayers = "SELECT Id FROM tblPlayers WHERE Game='" . $gamenumber. "' AND Joined='1'";
$resultCompetingPlayers = mysql_query($sqlCompetingPlayers);
while($row= mysql_fetch_array($resultCompetingPlayers))
{
    $PlayerId = $row['Id'];
    $sqlAlreadyHasPoints = "SELECT PlayerId FROM tblPlayerPoints WHERE PlayerId='" . $PlayerId . "'";
    $resultAlreadyHasPoints = mysql_query($sqlAlreadyHasPoints);
    $PointsRowFound = mysql_num_rows($resultAlreadyHasPoints);
    if($PointsRowFound < 1 ) {
        $sqlTotalPoints[] = '("' . $gamenumber . '", "FPS", "' . $PlayerId . '", "0")';
    }
}
echo 'INSERT INTO tblPlayerPoints (Game,GameNaam,PlayerId,PointsCollected) VALUES ' . implode(',',$sqlTotalPoints);

$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
echo '<b>Total Execution Time:</b> '.$execution_time.' secs';

这会导致正确的INSERT语句和22秒的总执行时间。

我曾经在while循环中插入而不是imploding,但执行时间更糟。

4 个答案:

答案 0 :(得分:3)

这一整段代码可以在一个SQL语句中完成。尝试使用INSERT INTO ... SELECT类型查询,并加入两个选择表,而不是循环第一个结果。即使没有表索引,您的数据大小也足够小,您不必担心时间限制。

答案 1 :(得分:1)

正如其他人所提到的,最好使用1个SQL语句。

"INSERT INTO tblPlayerPoints(Gamenumber,GameNaam,PlayerId,PointsCollected) ".
"SELECT tp.Id, 'FPS', tpp.PlayerID, 0 " .
" FROM tblPlayers tp " .
" JOIN tblPlayerPoints tpp ON tp.gamenumber = tpp.gamenumber " .
" WHERE tp.game = '" .$gamenumber ."' AND tp.joined = '1'"

您应该为WHERE子句(或JOIN)中存在的列添加索引:

CREATE INDEX IX_TBLPLAYERS_1 ON tblPlayers(gamenumber);
CREATE INDEX IX_TBLPLAYERS_2 ON tblPlayers(gamenumber, joined);

CREATE INDEX IX_TBLPLAYERPOINTS_1 ON tblPlayerPoints(gamenumber);

另外,我建议使用gamenumber的整数值并加入。整数查找起来要快得多。

答案 2 :(得分:1)

这是一个单独的SQL语句,这个与发布的另一个略有不同,因为它只会添加新行(如果不存在)。

INSERT INTO `tblPlayerPoints` (`Game`,`GameNaam`,`PlayerId`,`PointsCollected`)
SELECT `tblPlayers`.`Game`, 'FPS', `tblPlayers`.`Id`, 0 
    FROM `tblPlayers`
    LEFT JOIN `tblPlayerPoints` ON `tblPlayers`.`Id` = `tblPlayerPoints`.`PlayerId` AND `tblPlayers`.`Game` = `tblPlayerPoints`.`Game` 
WHERE `tblPlayers`.`Game`='" . $gamenumber. "' AND `tblPlayers`.`Joined`='1' AND `tblPlayerPoints`.`PointesCollected` IS NULL

答案 3 :(得分:-1)

最好的方法是使用以下查询。

INSERT INTO tblPlayerPoints
    (Gamenumber,GameNaam,PlayerId,PointsCollected)

SELECT col1,col2,col3,col4

FROM

tblPlayers //Your table from which you are retrieving data.