最近有用到mysql批量更新,使用最原始的批量update發現性能不好,將網上看到的總結一下一共有如下三種辦法:
1.批量update,一條記錄update一次,性能不好
update test_tbl set dr='2' where id=1;
2.replace into 或者insert into ...on duplicate key update
replace into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y');
或者使用
insert into test_tbl (id,dr) values mysql
3.建立臨時表,先更新臨時表,而後從臨時表中update
create temporary table tmp(id int(4) primary key,dr varchar(50));
insert into tmp values
update test_tbl, tmp set test_tbl.dr=tmp.dr where test_tbl.id=tmp.id;
注意:這種方法須要用戶有temporary 表的create 權限。
下面是上述方法update 100000條數據的性能測試結果:
逐條update
real
user
sys
replace into
real
user
sys
insert into on duplicate key update
real
user
sys
create temporary table and update:
real
user
sys
就測試結果來看,測試當時使用replace into性能較好。
replace into
replace into 操做本質是對重複的記錄先delete 後insert,若是更新的字段不全會將缺失的字段置爲缺省值
insert into 則是隻update重複記錄,不會改變其它字段。sql