mysql 批量修改优化方案

2023-12-13 04:37:23

一、场景批量修改多条数据
1、循环里修改

     public function test1foreach1()
    {
        $startTime = time();
        $table = M("table");
        $data =  $table->select();
        foreach ($data as $k => $v) {
            $table->where("id = {$v['id']}")->save(['type' => $v['type'] + 1,'league'=>{$v['league'].$k}]);
        }
        $endTime = time();
        echo  $endTime - $startTime;
        die;
    }

2、拼接case when

public function test1()
    {
        $startTime = time();
        $leagueValues = [];
        $typeValues = [];
        $ids = [];
        $table = M("table");
        $data =  $table->select();
        $updateSql = "UPDATE table SET league = CASE id";
        foreach ($data as $row) {
            $league = $row['league'] . $row['type'];
            $league = str_replace("'", "\'", $league);
            $type = $row['type'] - 1;
            $values1[] = "WHEN {$row['id']} THEN '{$league}'";
            $values2[] = "WHEN {$row['id']} THEN '{$type}'";
            $ids[] = $row['id'];
        }
        $ids = implode(',', $ids);
        $values1 = implode(' ', $values1);
        $values2 = implode(' ', $values2);
        $updateSql .= " {$values1} END , type = CASE id {$values2} END WHERE id IN ({$ids})";

        $result = M("table")->execute($updateSql);
        $endTime = time();
        echo  $endTime - $startTime;
        die;
    }

一万条数据第一种方式需要执行900多秒。第二种只需要3秒左右。

文章来源:https://blog.csdn.net/weixin_43926608/article/details/134870573
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。