Speed Up SQL Update Statement That Is Looped Through A Select Statement

允我心安 提交于 2019-12-11 16:55:36

问题


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;";


来源:https://stackoverflow.com/questions/53935927/speed-up-sql-update-statement-that-is-looped-through-a-select-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!