https://blog.csdn.net/qq_22227087/article/details/115898679

方案

批量update,一条记录update一次,性能很差

  1. update test_tbl set dr='2' where id=1;

replace into

  1. replace into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y');

insert into …on duplicate key update

  1. insert into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y') on duplicate key update dr=values(dr);

创建临时表,先更新临时表,然后从临时表中update

  1. create temporary table tmp(id int(4) primary key,dr varchar(50));
  2. insert into tmp values (0,'gone'), (1,'xx'),...(m,'yy');
  3. update test_tbl, tmp set test_tbl.dr=tmp.dr where test_tbl.id=tmp.id;
  4. 注意:这种方法需要用户有temporary 表的create 权限。

update 100000条数据的性能测试结果:

  1. 逐条update
  2. real 0m15.557s
  3. user 0m1.684s
  4. sys 0m1.372s
  5. replace into
  6. real 0m1.394s
  7. user 0m0.060s
  8. sys 0m0.012s
  9. insert into on duplicate key update
  10. real 0m1.474s
  11. user 0m0.052s
  12. sys 0m0.008s
  13. create temporary table and update:
  14. real 0m0.643s
  15. user 0m0.064s
  16. sys 0m0.004s

就测试结果来看,测试当时使用replace into性能较好。
replace into 和insert into on duplicate key update的不同在于:

  • replace into 操作本质是对重复的记录先delete 后insert,如果更新的字段不全会将缺失的字段置为缺省值
  • insert into 则是只update重复记录,不会改变其它字段。