在mysql中更新批量记录需要花费太多时间

时间:2017-05-22 11:14:24

标签: php mysql sql performance

我正在尝试更新超过100k行的大表。我从应用preg_match的表中获取数据,然后使用新值再次更新表。

问题是更新数据库中的所有记录需要数小时。

我正在使用的代码

$sql = "SELECT id, city_hotel, state, cc1 FROM hotel_names";
$result = $conn->query($sql);
$array = array();
if ($result->num_rows > 0) {
// output data of each row
 while($row = $result->fetch_assoc()) {
     $array[] = $row; 
  }
}
foreach ($array as $arr)
{       
    if (preg_match_all('/\(([A-Za-z0-9 ]+?)\)/', $arr['city_hotel'], $out))
        {
            if(!empty($out))
            {
                $STATE[] = $out[1];
                //print_r($STATE);
                foreach ($STATE as $state)
                {
                    $st = $state[0];
                    print_r($state) ;
    $stmt = $conn->prepare("UPDATE hotel_names SET state = ? WHERE id = ? ");
                    $stmt->bind_param('ss' ,$st, $arr['id']);
                    $stmt->execute();
                    echo "State Updated <br>";
                                if(preg_replace("/\([^)]+\)/","",$arr['city_hotel']))
                                {
                                    $city = preg_replace("/\([^)]+\)/","",$arr['city_hotel']);
                                    //echo $city = trim($city).'<br>';
                                    $stmt = $conn->prepare("UPDATE hotel_names SET  city_hotel = ? WHERE id = ? ");
                                    $stmt->bind_param('ss' , $city, $arr['id']);
                                    $stmt->execute();       
                                    echo "City Updated <br>";   
                                }
                }
            }
        }   
}

1 个答案:

答案 0 :(得分:0)

这需要时间,因为你在循环中一次又一次地执行sql。因此它生成了很多进程。你可以在执行过程中按照给定的链接执行多个查询。

(PDO PHP) The fastest way to update or insert multiple rows?