MySQL 批量操作数据

问个问题,平常在遇到批量操作数据的时候,循环操作和拼接sql批量操作该怎么选?批量比较多的数据会造成读取速度变慢,请问各位批量操作数据是用的什么方法?求指教

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2
da_house

我通常会尽量避免 循环里面 去做数据库操作,例如有批量插入的情况,我会处理完数据 一次性写入数据库。 希望能对您有所帮助。

3年前 评论
xiaoweiwei (楼主) 3年前

尽量避免循环查库,如果可以,尽量批量插入/更新,数据量特别大,可以先chunk一下,在批量操作,如果在循环里面用到了一些数据,可以先查询出来(集合),然后在循环内使用集合方法,增加where条件筛选等等。。。。 laravel 集合方法很强大,非常多的实用方法

$data = Good::where(条件)->get();
foreach($res as $item) {
    $current = $data->where('id',$item->goods_id)->first();
    // 处理相关逻辑
}

这样相当于只查询了一次数据库

批量插入,DB::insert(); 批量更新,updateBatch()

   //批量更新
    public function updateBatch($multipleData = [])
    {
        try {
            if (empty($multipleData)) {
                throw new \Exception("数据不能为空");
            }
            $tableName = DB::getTablePrefix() . $this->getTable(); // 表名
            $firstRow  = current($multipleData);

            $updateColumn = array_keys($firstRow);
            // 默认以id为条件更新,如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);
            // 拼接sql语句
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets      = [];
            $bindings  = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn   = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings  = array_merge($bindings, $whereIn);
            $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            return false;
        }
    }
3年前 评论
xiaoweiwei (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!