case when batch update

single value:
UPDATE categories
    SET display_order = CASE id
        WHEN 1 THEN 3
        WHEN 2 THEN 4
        WHEN 3 THEN 5
    END
WHERE id IN (1,2,3);
Multiple values:
UPDATE categories
    SET display_order = CASE id
        WHEN 1 THEN 3
        WHEN 2 THEN 4
        WHEN 3 THEN 5
    END,
    title = CASE id
        WHEN 1 THEN 'New Title 1'
        WHEN 2 THEN 'New Title 2'
        WHEN 3 THEN 'New Title 3'
    END
WHERE id IN (1,2,3);
mean: update the display_order field, if id=1, the value of display_order is 3, if id=2, the value of display_order is 4, and if id=3, the value of display_order is 5. 
That is, conditional statements are written together.
The where part here does not affect the execution of the code, but it will improve the efficiency of SQL execution. Ensure that the sql statement only executes the number of rows that need to be modified, there are only 3 rows of data to update, and the where clause ensures that only 3 rows of data are executed
Taking php as an example, construct this mysql statement:
$display_order = array(
    1 => 4,
    2 => 1,
    3 => 2,
    4 => 3,
    5 => 9,
    6 => 5,
    7 => 8,
    8 => 9
);
$ids = implode(',', array_keys($display_order));
$sql = "UPDATE categories SET display_order = CASE id ";
foreach ($display_order as $id => $ordinal) {
    $sql .= sprintf("WHEN %d THEN %d ", $id, $ordinal);
}
$sql .= "END WHERE id IN ($ids)";
echo $sql; 
mean: 8 records to update
Original address: http://www.jb51.net/article/41852.htm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325323251&siteId=291194637