单个查询中的多个mysql更新

时间:2012-02-12 23:17:30

标签: php mysql

我有一个名为member_photos的表,用于存储member_idphoto_idphoto_dirphoto_name,当有人编辑他的照片时,会发布一个数组内容关于照片的信息,发布的页面有一个包含照片信息的数组但我的问题是我使用foreach循环并逐个更新每张照片

 UPDATE member_photos 
    SET photo_name = '$newphotoname' 
  WHERE photo_id = '$photoid'

有效,但是当这个人有20张照片时,数组有20个项目,所以循环会做20个查询。有什么方法可以用单个查询更新所有照片吗?

1 个答案:

答案 0 :(得分:6)

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)
PHP中的

// An array containing the category ids as keys and the new positions as values
$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;

此信息的资源:http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/