公司新项目需要进行数据迁移,在使用测试数据库编写迁移脚本时,发现之前的数据库写法太占内存,所以记下更改后的代码,方便以后查看
原来写法:
$customer = $this->mysqli->query('select user_basic.*,parent_department,black_list.id as is_black,department.store_id as d_store from user_basic left join department on department.id = department_id left join black_list on black_list.phone = user_basic.phone order by user_basic.id');
$count = $this->count($this->mysqli, 'user_basic');
$time = time();
\DB::statement('SET FOREIGN_KEY_CHECKS = 0');
while($row = $customer->fetch_object()){
...
}
更改后:
//迭代器
public function cursor($connection, $sth)
{
while ($row = $sth->fetch_object()) {
@mysqli_next_result(${$connection});
yield $row;
}
}
...
//使用MYSQLI_USE_RESULT 后 再执行 mysql操作 可能会报Commands out of sync; you can't run this command now 目前我采用的是,另起一个数据库连接避免这个问题
$count = $this->count($this->mysqli, 'user_basic');
$customer = $this->mysqli->query('select user_basic.*,parent_department,black_list.id as is_black,department.store_id as d_store from user_basic left join department on department.id = department_id left join black_list on black_list.phone = user_basic.phone order by user_basic.id', MYSQLI_USE_RESULT);
$time = time();
\DB::statement('SET FOREIGN_KEY_CHECKS = 0');
foreach ($this->cursor($this->mysqli, $customer) as $row) {
...
}
优化前
Max usage:680.53MB
优化后
Max usage:18.53MB