方式一:使用for循环,进行一条条进行更新,可是这样更新数据的方式性能不好,也容易形成阻塞。html
因为这种方式的缺点,不少人都会想到,用一条sql语句实现批量更新。java
方式二:使用case when方式来实现批量更新sql
UPDATE mytable SET myfield = CASE id WHEN 1 THEN 'value' WHEN 2 THEN 'value' WHEN 3 THEN 'value' END WHERE id IN (1,2,3)
这种方式,更新数据库,将业务逻辑放在sql中,容易致使死锁。数据库
demo:ide
<!-- case when --> <update id="updateByBatchCaseWhen" parameterType="java.util.List"> update T_ORDER <trim prefix="set" suffixOverrides=","> <trim prefix="IO_TYPE = case" suffix="end,"> <foreach collection="list" item="i" index="index"> <if test="i.ioType!= null"> when ref=#{i.ref} then #{i.ioType} </if> </foreach> </trim> </trim> where <foreach collection="list" separator="or" item="i" index="index"> REF=#{i.ref} </foreach> </update>
方式三:replace into性能
replace into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y');
操做本质:对重复的记录先delete,后insert,若是更新的字段不全会将缺失的字段置为缺省值。测试
demo:spa
<!-- replace into --> <update id="updateByBatchReplace" parameterType="java.util.List"> replace into T_ORDER(ID,REF,IO_TYPE) values <foreach collection="list" separator="," item="i" index="index"> (#{i.id},#{i.ref},#{i.ioType}) </foreach> </update>
方式四:insert into ...on duplicate key update
3d
insert into test_tbl (id,dr) values (1,'2'),(2,'3'),...(x,'y') on duplicate key update dr=values(dr);操做本质:只update重复记录,不会改变其余字段
这种方式,要求有一个字段必须是主键或者惟一索引。code
demo:
<!-- insert into ...on duplicate key update --> <update id="updateByBatchDuplicate" parameterType="java.util.List"> insert into T_ORDER (ID,REF,IO_TYPE) values <foreach collection="list" separator="," item="i" index="index"> (#{i.id},#{i.ref},#{i.ioType}) </foreach> on duplicate key update IO_TYPE=VALUES(IO_TYPE) </update>
方式五:建立临时表,先更新临时表,而后从临时表中update
create 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;建立临时表,太损耗性能,通常不多用。
总结:
性能测试结果图:
方式一测试结果图:单条记录更新
方式二测试结果图:case when
方式三测试结果图:replace into
方式四测试结果图:duplicate
经小编测试,前四种方式,性能最好的,要数方式四:insert into ...on duplicate key update。