简体   繁体   English

单个查询中的多个mysql更新

[英]Multiple mysql updates in single query

i have a table named member_photos that stores member_id , photo_id , photo_dir and photo_name , when someone edited his photos, it posts an array containts info about photos, posted page has an array with photo informations but my problem is i use foreach loop and update every photo one by one like 我有一个名为member_photos的表,该表存储member_idphoto_idphoto_dirphoto_name ,当有人编辑他的照片时,它发布了有关照片的数组信息,发布的页面具有包含照片信息的数组,但是我的问题是我使用了foreach循环并更新了每个一张一张地合影

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

that works but when this guy has 20 photos, array has 20 items so loop will do 20 queries. 可以,但是当这个人有20张照片时,数组有20个项目,因此循环将执行20个查询。 Is there any way that i can update all photos with single query? 有什么方法可以通过一次查询更新所有照片?

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)

in PHP 在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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM