3

我有以下代码:

$query = mysql_query("SELECT * FROM mytable");

while($row = mysql_fetch_assoc($query)){
    mysql_query("INSERT INTO mytable2 (col1, col2) 
                 VALUES ('".$row['val1']."', '".$row['val2']."')");
}

可以理解,脚本在大约 150,000 次查询时超时......除了增加脚本内存之外,防止超时的最佳方法是什么?

4

2 回答 2

6

为什么不将其作为单个查询运行???

$SQL = "INSERT INTO mytable2 (col1,col2) SELECT val1,val2 FROM mytable";
$query = mysql_query($SQL); 

选择

您也可以一次限制您的 INSERT 200

$query = mysql_query("SELECT * FROM mytable"); 
$commit_count = 0;    
$commit_limit = 200;
$comma = "";
$SQL = "INSERT INTO mytable2 (col1, col2) VALUES ";
while($row = mysql_fetch_assoc($query)){ 
    $SQL .= $comma . "('".$row['val1']."','".$row['val2']."')";
    $comma = ",";
    $commit_count++;
    if ( $commit_count == $commit_limit )
    {
        mysql_query($SQL);
        $SQL = "INSERT INTO mytable2 (col1, col2) VALUES ";
        $commit_count = 0;    
        $comma = "";
    }
} 
if ( $commit_count > 0 ) { mysql_query($SQL); }

您可以将 更改$commit_limit为任何合理的正数。

于 2012-04-10T17:15:50.383 回答
3

您应该考虑使用INSERT ... SELECT语句而不是运行大量的单个插入。

于 2012-04-10T17:15:51.210 回答