MySQL批量更新的常用方法
批量更新一般在批處理系統(tǒng)或者定時任務(wù)中比較常見,常見的訴求就是對表中多條數(shù)據(jù)進(jìn)行更新(待更新的值是不一樣的麻削,這個區(qū)別于update ... where in(...))
1.利用case ... when ... 方式批量更新
特點:適合數(shù)據(jù)量小的更新妆档,數(shù)據(jù)量大時可能會產(chǎn)生間隙鎖僻爽,甚至表鎖,會影響性能贾惦,這個需要留意
常見的sql腳本如下:
UPDATE t_demo_audit_order SET
prod_no = CASE id WHEN 1 THEN 'C1' WHEN 2 THEN 'C2' WHEN 3 THEN 'C3' WHEN 4 THEN 'C4' END,
busi_no = CASE id WHEN 1 THEN 'B1' WHEN 2 THEN 'B2' WHEN 3 THEN 'B3' WHEN 4 THEN 'B4' END
WHERE id IN (1, 2, 3, 4)
mybatis動態(tài)拼接的sql腳本如下:
<update id="batchUpdateByPrimaryKey" parameterType="java.util.List">
update t_demo_audit_order set
prod_no = case id
<foreach collection="list" item="item">
when #{item.id} then #{item.prodNo}
</foreach>
end,
busi_no = case id
<foreach collection="list" item="item">
when #{item.id} then #{item.busiNo}
</foreach>
end
where id in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item.id}
</foreach>
</update>
2.批量執(zhí)行單條update語句
特點:可以充分利用索引胸梆,有較好的性能畸冲;
注意:sql的大小不能超過數(shù)據(jù)庫的限制昧识,否則會失敗。一個批次最大可以執(zhí)行多少條update語句取董,這個沒有絕對的數(shù)據(jù)量淌,需要依據(jù)自己的表結(jié)構(gòu)及數(shù)據(jù)量在測試環(huán)境進(jìn)行
嘗試疑苫,找到最佳數(shù)量欠母。比如你可以依次執(zhí)行1000條淌铐,2000條,3000條菠发,然后對比性能即可選出理想的數(shù)量
ps: 數(shù)據(jù)庫連接配置需要增加參數(shù) allowMultiQueries=true
sql腳本如下:
update demo_record set test_order_no = 'bar01', test_dt = 'xxx' where id = 1 ;
update demo_record set test_order_no = 'bar02', test_dt = 'xxx' where id = 2 ;
update demo_record set test_order_no = 'bar03', test_dt = 'xxx' where id = 3 ;
update demo_record set test_order_no = 'bar04', test_dt = 'xxx' where id = 4 ;
update demo_record set test_order_no = 'bar05', test_dt = 'xxx' where id = 5 ;
update demo_record set test_order_no = 'bar05', test_dt = 'xxx' where id = 6 ;
......
mybatis動態(tài)拼接的sql腳本如下:
<update id="batchUpdateByPrimaryKey" parameterType="java.util.List">
<foreach collection="list" item="item" open="" close="" separator=";">
update demo_record set
test_order_no = #{item.testOrderNo},
test_dt = #{item.testDt}
where id = #{item.id}
</foreach>
</update>
之前處理的一個需求王滤,滿足自己的業(yè)務(wù)需求即可贺嫂,sql耗時如下: