加快通过选择语句循环的SQL更新语句

时间:2018-12-26 18:50:23

标签: mysql join sql-update left-join recordset

在代码中找到需要31分钟(1900秒)才能完成的SQL查询。首先,一条select语句将抓取1955行,然后代码循环遍历这些行,以基于记录集内的数字运行更新。它运行的表有14,000行。我该如何加快速度?

$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);
            }
        }

尝试使用以下方法,但显示错误代码:1054。“ where子句”中的未知列“ dids.did”

 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 个答案:

答案 0 :(得分:1)

对SQL查询进行序列化通常会导致性能下降。您可以在一条语句中完成全部操作:

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