简体   繁体   English

使用单个查询更新多个记录以提高性能

[英]Update multiple records using a single query for performance

I am having an update query inside a loop which get executed thousands of times. 我在一个循环中执行了一个更新查询,该查询被执行了数千次。

All goes well but problem is that it takes lot of time for all updates. 一切顺利,但问题是所有更新花费大量时间。

If I concatenate/combine all update queries in a single string like this: 如果我将所有更新查询串联/合并为一个字符串,如下所示:

$update_query = "";
while(condition)
{
    $update_query = $update_query  . " update table set ... ; ";
}

Then execute $update_query single time, will it be helpful? 然后一次执行$ update_query ,对您有帮助吗?

Or what else I can do for better performance? 还是我可以做些什么以获得更好的性能? Any hint or suggestion? 有什么提示或建议吗?

What you're looking for is a batch update query, something like: 您要查找的是批处理更新查询,例如:

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)

You can use INSERT ... ON DUPLICATE KEY UPDATE 您可以使用INSERT ... ON重复键更新

INSERT INTO table (id, value) VALUES (1, 'value1'), (2, 'value2')
ON DUPLICATE KEY UPDATE
value = VALUES(value)

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

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