Speed Up SQL Update Statement That Is Looped Throu

2019-08-26 06:43发布

问题:

Found a SQL query in code that takes 31 minutes to complete (1900 seconds). First a select statement grabs 1955 rows, then the code loops through these rows to run an update based on a number inside that recordset. The table it runs through has 14,000 rows. How can I speed this up?

$sql = "select id, did, customer_id from dids";
        $rs = $db->PDOquery($sql, $qry_arr);
        //Loop through all DIDs and attach to cdrs  select id, did, customer_id from dids   
        while($row=$rs->fetch()){                           
            $qry_arr = array(':did_id' => $row['id'],
                        ':customer_id' => $row['customer_id'],
                        ':did' => $row['did']);
            $sql = "update ".$billing_table."  c ";
            $sql .= "set c.did_id = :did_id, c.customer_id = :customer_id  ";
            $sql .= "where c.customer_id = 0 and c.telcom_num = :did ";

            $result=$db->PDOquery($sql, $qry_arr);
            set_time_limit(30);  //Reset time limit after each query
            if (!$result) {
                error_log(date("Y/m/d h:i:sa").": "."\nError In Sql.\n".$sql, 3, $cron_log);
            }
        }

Tried using the following but get an error saying Error Code: 1054. Unknown column 'dids.did' in 'where clause'

 UPDATE ".billing_table." SET ".billing_table.".did_id = dids.id, ".billing_table.".customer_id = dids.customer_id WHERE dids.did =  ".billing_table.".telcom_num

回答1:

Serializing the SQL queries often leads into bad performance. You can do all in one statement:

$sql = "update ".$billing_table." c ".
       "inner join dids d on d.did=c.telcom_num ".
       "set c.did_id = d.id, c.customer_id = d.customer_id ".
       "where c.customer_id = 0;";