Batch updatemysqlIn mysql we may use # for batch update ##update,replace into to operate, the following details mysqlBatch update and performance.
The update statement is very simple. It updates a certain field of a piece of data. It is usually written like this:
1 |
|
mysql is also very simple, just modify itwhereThat's it:
1 |
|
other_values' is separated by a comma (,) string, such as: 1,2,3
Then if multiple pieces of data are updated to different values, many people may write like this:1 2 3 4 |
|
update once, which has poor performance and can easily cause blocking.
So can batch updates be implemented with onesql statement? mysql does not provide a direct method to implement batch updates, but it can be achieved with some tricks.
1 2 3 4 5 6 7 |
|
case when is used here to achieve batch updates.
For example:1 2 3 4 5 6 7 |
|
sql means , update the display_order field. If id=1 , then the value of display_order is 3, if id=2 then the value of display_order is 4, if id=3 then the value of display_order is 5.
is to write the conditional statements together. Thewhere part here does not affect the execution of the code, but will improve the efficiency of sql execution. Make sure that the sql statement only executes the number of rows that need to be modified. Here, only 3 pieces of data are updated, while The where clause ensures that only 3 rows of data are executed.
If you update multiple values, you only need to modify it slightly:1 2 3 4 5 6 7 8 9 10 11 12 |
|
mysql The statement updated multiple records.
But to use it in business, it needs to be combined with server-side language. Here, takephp as an example to construct this mysql Statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
这个例子,有8条记录进行更新。代码也很容易理解,你学会了吗
当我使用上万条记录利用mysql批量更新,发现使用最原始的批量update发现性能很差,将网上看到的总结一下一共有以下三种办法:
1.批量update,一条记录update一次,性能很差
1 |
|
2.replace into 或者insert into ...on duplicate key update
1 |
|
或者使用
1 |
|
3.创建临时表,先更新临时表,然后从临时表中update
1 2 3 |
|
注意:这种方法需要用户有temporary 表的create 权限。
下面是上述方法update 100000条数据的性能测试结果:
逐条update
real 0m15.557s
user 0m1.684s
sys 0m1.372s
replace into
real 0m1.394s
user 0m0.060s
sys 0m0.012s
insert into on duplicate key update
real 0m1.474s
user 0m0.052s
sys 0m0.008s
create temporary table and update:
real 0m0.643s
user 0m0.064s
sys 0m0.004s
就测试结果来看,测试当时使用replace into性能较好。
replace into 和insert into on duplicate key update的不同在于:
replace into 操作本质是对重复的记录先delete 后insert,如果更新的字段不全会将缺失的字段置为缺省值
insert into 则是只update重复记录,不会改变其它字段。
1 2 |
|
原因是在safe mode下,要强制安全点,update只能跟where了, 要取消这个限制,可以:
1 |
|
以上就是mysql进阶(十四) 批量更新与批量更新多条记录的不同值实现方法 的内容,更多相关内容请关注PHP中文网(www.php.cn)!