通常情况下,我们会使用以下SQL语句来更新字段值:
UPDATE mytable SET myfield='value' WHERE other_field='other_value';UPDATE mytable SET myfield='value' WHERE other_field='other_value';
foreach ($display_order as $id => $ordinal) { $sql="UPDATE categories SET display_order = $ordinal WHERE id = $id"; mysql_query($sql); }
UPDATE mytable SET myfield = CASE other_field 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 1 WHEN 3 THEN 2 END WHERE id IN (1,2,3)
如果你需要更新一行记录的多个字段,可以用以下SQL语句:
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语句 } $sql .= "END WHERE id IN ($ids)"; echo $sql; mysql_query($sql);
文章参考出自:http://www.jbxue.com/db/mysql_update_h4hxn37M2.html
原文地址:http://blog.csdn.net/web361/article/details/42455341