mysql 批量更新

来源:互联网 发布:java大数据是什么 编辑:程序博客网 时间:2024/05/23 02:04
最近有用到mysql批量更新,使用最原始的批量update发现性能很差,将网上看到的总结一下一共有以下三种办法:1.批量update,一条记录update一次,性能很差update test_tbl set dr='2' where id=1;2.replace into 或者insert into ...on duplicate key updatereplace into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y');注:如果一个表中有多个字段,而只想更改一个字段的值,最好不要用replace into ,不然其他的字段的值会被设置为空,除非把原值带上或者使用insert into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y') on duplicate key update dr=values(dr);3.创建临时表,先更新临时表,然后从临时表中updatecreate temporary table tmp(id int(4) primary key,dr varchar(50));insert into tmp values (0,'gone'), (1,'xx'),...(m,'yy');update test_tbl, tmp set test_tbl.dr=tmp.dr where test_tbl.id=tmp.id;注意:这种方法需要用户有temporary 表的create 权限。此方法挺好用下面是上述方法update 100000条数据的性能测试结果:逐条updatereal   0m15.557suser   0m1.684ssys   0m1.372sreplace intoreal   0m1.394suser   0m0.060ssys   0m0.012sinsert into on duplicate key updatereal   0m1.474suser   0m0.052ssys   0m0.008screate temporary table and update:real   0m0.643suser   0m0.064ssys   0m0.004s就测试结果来看,测试当时使用replace into性能较好。replace into 和insert into on duplicate key update的不同在于:replace into 操作本质是对重复的记录先delete 后insert,如果更新的字段不全会将缺失的字段置为缺省值insert into 则是只update重复记录,不会改变其它字段。

0 0
原创粉丝点击