【问题标题】:How to reduce the insertion time of data with Codeigniter?如何使用 Codeigniter 减少数据的插入时间?
【发布时间】:2018-05-27 00:44:37
【问题描述】:

我通过以下方式将数据插入数据库:

控制器:

foreach($cData as $data){

    $ins['name'] = $data['name'];

    $bonus = $this->calBonus($data['bonus']); //calculates bonus.

    $ins['bonus'] = $bonus;

    //similarly there are few more data which are assigned to the $ins array;

    $res = $this->myModel->insertData($ins); // for inserting data;

}

型号:

function insertData($ins){
    $res = $this->db->insert('bonus',$ins);
    if($res){
        return 1;
    }
    else{
        return 0;
    }
} 

我在$cdata 中有300000 数据。对于一个数据插入,它占用100 milliseconds。因此,要完全插入,需要 8 个多小时。

现在如何优化这个插入?有没有更好的方法来做到这一点?

【问题讨论】:

  • 你是在解析 csv 文件还是什么?
  • 将整个事情包装在一个事务中。它将执行得更快。使用 PHP 的 mysqli 函数而不是 CodeIgniter 的 DB 库也可能会减少执行时间。
  • @DanyalSandeelo 不是 CSV,$cData 是从数据库中获取数据。
  • 那你做错了兄弟,有办法在数据库层得到它。像这样使用insert into table(col1, col2, col3) select col1,col2, col3 from table_2,这将在数据库上完成,而且速度非常快。
  • @BrianGottier 我实际上有疑问如果在插入之前有一些逻辑要执行,这是优化的:1)通过 CodeIgniter 插入。 2)通过PHP,MySQL插入。 3) 在 MySQL 中编写存储过程。

标签: php mysql codeigniter optimization


【解决方案1】:

使用批量插入功能

$mainArray = array();
foreach($cData as $data){

    $ins['name'] = $data['name'];

    $bonus = $this->calBonus($data['bonus']); //calculates bonus.

    $ins['bonus'] = $bonus;
    // push array in main array
    array_push($mainArray,$ins);
}

if($mainArray != array()){

    $this->db->insert_batch('YOUR_TABLE_NAME', $mainArray)
}

参考:Here

【讨论】:

  • 成功了,竞争数组在 3 秒内插入。谢谢。
  • 乐于助人:)
  • 我糟糕的 5k 记录在 3 秒内被插入,这比正常插入要好得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2015-05-29
  • 2014-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多