mysql—加速循环通过select语句的sql update语句

1cosmwyk  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(377)

在代码中找到一个sql查询,完成该查询需要31分钟(1900秒)。首先,select语句获取1955行,然后代码循环遍历这些行以基于该记录集中的数字运行更新。它所经过的表有14000行。我怎样才能加快速度?

$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
lndjwyie

lndjwyie1#

序列化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;";

相关问题