duanji7182 2012-09-13 12:28
浏览 11
已采纳

如何使用mysql执行多个更新查询

I am trying to execute multiple update queries at a time. Please have a look into below mentioned code.

Actual code block:

$relist_item_id  = $_REQUEST['relist_item_id'];   // an array
$relist_item_num = count($relist_item_id);

for($j = 0; $j < $relist_item_num; $j++){
  $item_id = $relist_item_id[$j]; 
  $update_query = "UPDATE items SET ActiveItem=1 WHERE id=$item_id";
  mysql_query($update_query);
}

The above code will execute each query one by one. But i want to execute all the query at a time and so i have tried the below code.

$update_query = '';
for($j = 0; $j < $relist_item_num; $j++){
  $item_id = $relist_item_id[$j]; 
  $update_query .= "UPDATE items SET ActiveItem=1 WHERE id=$item_id;";
}
mysql_query($update_query); 

The above mentioned code is not executing/ updating the record. But, i want to execute in similar way. Is it possible to do so?

Using "SQL" in phpmyadmin, i have checked that we can execute more than one query at a time i.e. several update query can be executed at a time. For eg. the below mentioned update query will be executed at a time.

UPDATE items SET ActiveItem=1 WHERE id=1;UPDATE items SET ActiveItem=1 WHERE id=5;UPDATE items SET ActiveItem=1 WHERE id=10;UPDATE items SET ActiveItem=1 WHERE id=12;UPDATE items SET ActiveItem=1 WHERE id=15;UPDATE items SET ActiveItem=1 WHERE id=16;UPDATE items SET ActiveItem=1 WHERE id=20;

I would also like to know that is there any limit on the query like we can execute maximum of 20 queries at a time or so?

My actual target is to save the execution time as there can be a huge for loop and it may take many time to execute each and every query one by one. My above approach may not be correct. But, your idea can help me to do so.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dougan1465 2012-09-13 12:31
    关注

    Why not use an in function like this:

    $relist_item_id  = $_REQUEST['relist_item_id'];   // an array
    $query="UPDATE items 
        SET ActiveItem=1 WHERE id in (".implode(', ', $relist_item_id).")";
    

    Assumes that the values are numeric and don't need to be encapsed in single quotes. If they are, this should work:

    $query="UPDATE items 
        SET ActiveItem=1 WHERE id in ('".implode("', '", $relist_item_id)."')";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题