简体   繁体   English

通过MySql命令中的foreach循环加快执行速度

[英]speed up execution by foreach loop in MySql command

I have a PHP foreach statement, looping through a large number of $icons . 我有一个PHP foreach语句,遍历了大量$icons

For each icon, the DB-column sequence needs to be updated. 对于每个图标,需要更新DB列sequence As follows: 如下:

foreach ($icons as $key => $icon) {
    // MySql pseudo-code:
    UPDATE `tbl_icon2album` 
    SET `sequence`= $key +1 
    WHERE iconID= $icon['id']       
}

My problem : this becomes very slow for a large number of icons. 我的问题 :对于大量图标,这变得非常缓慢。

My question : Can I speed this up by executing one MySql command that would somehow include the foreach loop? 我的问题 :我可以通过执行一个MySql命令来加快速度吗,该命令将以某种方式包括foreach循环?

Much obliged... 多谢...

You could put all your updates in another table, and update using a single query, eg 您可以将所有更新放在另一个表中,并使用单个查询进行更新,例如

 UPDATE tbl_icon2album, some_other_table
 SET    sequence = some_other_table.new_key_value
 WHERE  iconID = some_other_table.icon_reference

How many keys are you updating? 您要更新多少个密钥? Is it the iteration that is slow, or are you doing this thousands of times? 是迭代很慢,还是您要执行数千次?

You could use the "in" clause. 您可以使用“ in”子句。

ie: 即:

 update table set key=key+1 where blah in ('1','2','3');

and you could iterate through the for loop to construct a variable passed to in: 您可以遍历for循环来构造一个传递给in的变量:

ie: 即:

 $iconlist = "";
 foreach ($icons as $key => $icon) {
   if (!$iconlist) { $iconlist = "($icon" }
   else 
   { $iconlist .= ",$icon" }
 }
 if ($iconlist) { 
   $iconlist .= ")";
   $query = "update table set key=key+1 where icon in $iconlist";

 }

If you use prepared statements then you can prepare the query once, bind the parameters, and then execute within the loop. 如果使用准备好的语句,则可以准备一次查询,绑定参数,然后在循环内执行。 This could be faster as it is usually preparing the query that takes up time. 这可能更快,因为它通常准备耗时的查询。 For example: 例如:

$stmt = $mysqli->prepare("

  UPDATE
    `tbl_icon2album`
  SET
    `sequence` = ?
  WHERE
    `iconID` = ?

");

$stmt->bind_param('ii', $sequence, $icon_id);

foreach ($icons as $key => $icon)
{

  $sequence = $key + 1;

  $icon_id = $icon['id'];

  $stmt->execute(); 

}

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

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