首先mysql更新数据的某个字段,一般这样写:
UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value'; |
也可以这样用in指定要更新的记录:
UPDATE mytable SET myfield = 'value' WHERE other_field in ('other_values'); |
这里注意 ‘other_values' 是一个逗号(,)分隔的字符串,如:1,2,3
如果更新多条数据而且每条记录要更新的值不同,可能很多人会这样写:
foreach ($values as $id => $myvalue) { $sql = "UPDATE mytable SET myfield = $myvalue WHERE id = $id"; mysql_query($sql);} |
即是循环一条一条的更新记录。一条记录update一次,这样性能很差,也很容易造成阻塞。
那么能不能一条sql语句实现批量更新呢?
mysql并没有提供直接的方法来实现批量更新,但是可以用点小技巧来实现。
UPDATE mytable SET myfield = CASE id WHEN 1 THEN 'myvalue1' WHEN 2 THEN 'myvalue2' WHEN 3 THEN 'myvalue3' ENDWHERE other_field ('other_values') |
如果where条件查询出记录的id不在CASE范围内,myfield将被设置为空。
如果更新多个值的话,只需要稍加修改:
UPDATE mytable SET myfield1 = CASE id WHEN 1 THEN 'myvalue11' WHEN 2 THEN 'myvalue12' WHEN 3 THEN 'myvalue13' END, myfield2 = CASE id WHEN 1 THEN 'myvalue21' WHEN 2 THEN 'myvalue22' WHEN 3 THEN 'myvalue23' ENDWHERE id IN (1,2,3) |
这里以php为例,构造这两条mysql语句:
1、更新多条单个字段为不同值, mysql模式
$ids_values = array( 1 => 11, 2 => 22, 3 => 33, 4 => 44, 5 => 55, 6 => 66, 7 => 77, 8 => 88,); $ids = implode(',', array_keys($ids_values ));$sql = "UPDATE mytable SET myfield = CASE id ";foreach ($ids_values as $id=> $myvalue) { $sql .= sprintf("WHEN %d THEN %d ", $id, $myvalue);}$sql .= "END WHERE id IN ($ids)";echo $sql.";<br/>"; |
输出:
UPDATE mytable SET myfield = CASE id WHEN 1 THEN 11 WHEN 2 THEN 22 WHEN 3 THEN 33 WHEN 4 THEN 44 WHEN 5 THEN 55 WHEN 6 THEN 66 WHEN 7 THEN 77 WHEN 8 THEN 88 END WHERE id IN (1,2,3,4,5,6,7,8); |
2、更新多个字段为不同值, PDO模式
$data = array(array('id' => 1, 'myfield1val' => 11, 'myfield2val' => 111), array('id' => 2, 'myfield1val' => 22, 'myfield2val' => 222));$where_in_ids = implode(',', array_map(function($v) {return ":id_" . $v['id'];}, $data));$update_sql = 'UPDATE mytable SET';$params = array();$update_sql .= ' myfield1 = CASE id';foreach($data as $key => $item) { $update_sql .= " WHEN :id_" . $key . " THEN :myfield1val_" . $key . " "; $params[":id_" . $key] = $item['id']; $params[":myfield1val_" . $key] = $item['myfield1val'];}$update_sql .= " END";$update_sql .= ',myfield2 = CASE id';foreach($data as $key => $item) { $update_sql .= " WHEN :id_" . $key . " THEN :myfield2val_" . $key . " "; $params[":id_" . $key] = $item['id']; $params[":myfield1va2_" . $key] = $item['myfield2val'];}$update_sql .= " END";$update_sql .= " WHERE id IN (" . $where_in_ids . ")";echo $update_sql.";<br/>";var_dump($params); |