mysql 批量修改优化方案

一、场景批量修改多条数据
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秒左右。

你可能感兴趣的:(mysql,数据库)