Multiple Updates in MySQL

前端 未结 17 1306
南方客
南方客 2020-11-22 01:31

I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?

Edit: For example I have the followi

17条回答
  •  醉梦人生
    2020-11-22 01:56

    UPDATE `your_table` SET 
    
    `something` = IF(`id`="1","new_value1",`something`), `smth2` = IF(`id`="1", "nv1",`smth2`),
    `something` = IF(`id`="2","new_value2",`something`), `smth2` = IF(`id`="2", "nv2",`smth2`),
    `something` = IF(`id`="4","new_value3",`something`), `smth2` = IF(`id`="4", "nv3",`smth2`),
    `something` = IF(`id`="6","new_value4",`something`), `smth2` = IF(`id`="6", "nv4",`smth2`),
    `something` = IF(`id`="3","new_value5",`something`), `smth2` = IF(`id`="3", "nv5",`smth2`),
    `something` = IF(`id`="5","new_value6",`something`), `smth2` = IF(`id`="5", "nv6",`smth2`) 
    

    // You just building it in php like

    $q = 'UPDATE `your_table` SET ';
    
    foreach($data as $dat){
    
      $q .= '
    
           `something` = IF(`id`="'.$dat->id.'","'.$dat->value.'",`something`), 
           `smth2` = IF(`id`="'.$dat->id.'", "'.$dat->value2.'",`smth2`),';
    
    }
    
    $q = substr($q,0,-1);
    

    So you can update hole table with one query

提交回复
热议问题