mysql - PHP 批量插入的时候 判断数据表里面是否重复怎么优化
怪我咯
怪我咯 2017-04-17 16:51:55
0
4
663

场景:从第三方接口获取到数据 比如 获取到了 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);
}
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
PHPzhong

Ensure that it is only processed in the database, just set it as unique.
This does not require PHP to process.

迷茫

Set joint primary key

洪涛

Add a unique index to fields that cannot be repeated

迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template