标签:style blog color 使用 ar for 数据 sp div
mysql更新语句很简单,更新一条数据的某个字段,一般这样写:
UPDATE mytable SET myfield = ‘value‘ WHERE other_field = ‘other_value‘;
如果更新同一字段为同一个值,mysql也很简单,修改下where即可:
UPDATE mytable SET myfield = ‘value‘ WHERE other_field in (‘other_values‘);
这里注意 ‘other_values’ 是一个逗号(,)分隔的字符串,如:1,2,3
那如果更新多条数据为不同的值,可能很多人会这样写:
foreach ($display_order as $id => $ordinal) { $sql = "UPDATE categories SET display_order = $ordinal WHERE id = $id" mysql_query($sql); }
即是循环一条一条的更新记录。一条记录update一次,这样性能很差,也很容易造成阻塞。
那么能不能一条sql语句实现批量更新呢?mysql并没有提供直接的方法来实现批量更新,但是可以用点小技巧来实现。
UPDATE mytable SET myfield = CASE id WHEN 1 THEN ‘value‘ WHEN 2 THEN ‘value‘ WHEN 3 THEN ‘value‘ END WHERE id IN (1,2,3)
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)
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)
$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;
这个例子,有8条记录进行更新。代码也很容易理解,你学会了吗?
标签:style blog color 使用 ar for 数据 sp div
原文地址:http://www.cnblogs.com/ccode/p/4008094.html