bulk updating a list of values from a list of ids

后端 未结 1 1804
野的像风
野的像风 2021-01-14 02:17

I\'m frequently facing this issue, as an Oracle user, playing around with MySql.

Be the following situation:

  • a list of ids (1, 2, 3, ..., n)
  • a
相关标签:
1条回答
  • 2021-01-14 02:28

    Here is one way to do this using one query. It won't be the prettiest-formatted query, but it will be just one.

    <?php
    
    $id_list = implode(',', $ids);
    $whens = implode(
        "\n    ",
        array_map(
            function ($id, $value) {
                return "WHEN {$id} THEN {$value}";
            },
            $ids,
            $values
        )
    );
    
    $sql = "
        UPDATE value
        SET value = CASE id
        {$whens}
        END
        WHERE id IN ({$id_list})
    ";
    ?>
    

    See my modified SQLFiddle.

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