场景:从第三方接口获取到数据 比如 获取到了 500 条,然后批量插入到表,但是要保证唯一。代码如果是这样的(name 字段有索引的情况下怎么才能最大化的优化),这样的结果是有500次的I/O 这个逻辑怎么优化最佳呢;这里还有个场景如果当这 500条插入成功后马上进行二次查询第三方接口然后再批量插入,主要是考虑到第二种情况:
$datas = [];
$Apps = new Apps();
foreach ($lists as $k=>$v){
$name = $v['name'];
$res = $Apps->where(['name' => $name])
->field('name')
->find();
//如果没有记录
if (empty($res)){
$datas[] = ['name' => $name];
}
}
if (empty($datas)){
//批量插入
$Apps->saveAll($datas);
}
PHPz2017-04-17 16:53:55
Ensure that it is only processed in the database, just set it as unique.
This does not require PHP to process.
迷茫2017-04-17 16:53:55
First add a unique index to the field, and then change the SQL to this, INSERT INTO xx (yy)VALUES(?) ON DUPLICATE KEY UPDATE yy=?
But when the unique key is repeated, update the field. You can also ignore the repetition. OK, do not modify INSERT IGNORE INTO