Mysql批量更新数据

方式一:使用for循环,进行一条条进行更新,但是这样更新数据的方式性能很差,也容易造成阻塞。

   由于这种方式的缺点,很多人都会想到,用一条sql语句实现批量更新。

方式二:使用case when方式来实现批量更新

   

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:

<!-- 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:

<!-- 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

insert into test_tbl (id,dr) values  (1,'2'),(2,'3'),...(x,'y') on duplicate key update dr=values(dr);
     操作本质:只update重复记录,不会改变其他字段

     这种方式,要求有一个字段必须是主键或者唯一索引。

    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。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值