dongyumiao5210 2019-06-11 11:22
浏览 176

循环时UPDATE查询表单,代码很慢

i have in my Laravel App this code: i read every line in a .csv file and a want to update a value. But the multiple's update query are very slow with a .csv of 8k rows. How i can speed this code ? Thanks

DB::beginTransaction();

        try {

            $delimiter = ",";
            $firstLine = true;

            if ($handle !== FALSE) {
                $position = 1;
                while (($csv_line = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {

                    if ($firstLine == true) {
                        $firstLine = false;
                        continue;
                    }

                    $player_uid = $csv_line[0];

                    DB::table('scores')
                        ->where('season_uid', $season_uid)
                        ->where('day', $day)
                        ->where('player_uid', $player_uid)
                        ->update(['position' => $position]);

                    $position++;

                }
                fclose($handle);
            }

            DB::commit();
            return true;

        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            return false;
        }
  • 写回答

2条回答 默认 最新

  • douhua1890 2019-06-11 11:36
    关注

    MySQL doesn't support mass updates, but there is a neat trick to replace updates with inserts using ON DUPLICATE KEY UPDATE clause. That way you can actually update your records in bulks. Check out this answer for some examples.

    To my knowledge though Laravel doesn't support this clause in it's query builder, so you will have to generate query manually and issue it via DB::statement(). Make sure to chunk your incoming rows (by 100, for example) and you will see noticeable boost in speed.

    But do realize that updating 8k rows is not a cheap operation. The best practice would be to delegate it to a separate job and set up queues in your application so that those updates can be processed in the background by your workers separately. You can read more about jobs and queues in the official documentation.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器