Update multiple rows with one query

前端 未结 3 2001
孤独总比滥情好
孤独总比滥情好 2021-01-06 09:18

How can I update hundreds of rows at once?

Like: UPDATE table SET a = ? WHERE b = ? AND c = 1

but for many rows. The ? parameters a

相关标签:
3条回答
  • 2021-01-06 09:54

    To do it in a single run of a query, you'd need to use a CASE and assemble the parameters programmatically. SQL doesn't support variadic prepared statements, and only simple values can be parameterized.

    Alternatively, define a statement to only take data for one row at a time and run the query in a loop. Repeated execution is how prepared statements are designed to be used for cases like this.

    try {
        $query = $db->prepare('UPDATE table SET a = ? WHERE b = ? AND c = 1');
        foreach ($as as $i => $a) {
            $query->execute(array($a, $bs[$i]));
        }
    } catch (PDOException $e) {
        ...
    }
    
    0 讨论(0)
  • 2021-01-06 09:59

    Another way would be to insert your key value pairs (all at once) into a temporary table then do something like this:

    UPDATE table t
    SET t.a = (SELECT p.a FROM tmp p WHERE p.b = t.b)
    WHERE t.b IN (SELECT p.b FROM tmp p) AND t.c = 1
    
    0 讨论(0)
  • 2021-01-06 10:07

    Use the CASE method as described in the link you provided, but build the query dynamically with the values you want.

    Likely, this will be built with a for loop similar to how you're already doing it, but you will end up with a single query rather than querying your database every iteration.

    0 讨论(0)
提交回复
热议问题