Mysql 批量修改四种方式效率对比
批量修改方案
第一种 for循环
每循环一次,执行一次update,
1000.for i( 单条update sql )
这个效率很差.
第二种 foreach
<!-- 批量更新第一种方法,通过接收传进来的参数list进行循环着组装sql -->
<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item">
update people
<set>
<if test="item.firstName != null">
first_name = #{item.firstName},
</if>
<if test="item.lastName != null">
last_name = #{item.lastName},
</if>
</set>
where id = #{item.id};
</foreach>
</update>
第三种 case when
这句sql的意思是,更新display_order 字段,如果id=1 则display_order 的值为3,如果id=2 则 display_order 的值为4,如果id=3 则 display_order 的值为5。 即是将条件语句写在了一起。 这里的where部分不影响代码的执行,但是会提高sql执行的效率。确保sql语句仅执行需要修改的行数,这里只有3条数据进行更新,而where子句确保只有3行数据执行。
UPDATE categories
SET display_order = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END
WHERE id IN (1,2,3)
第四种 replace into
replace into 操作本质是对重复的记录先delete 后insert,如果更新的字段不全会将缺失的字段置为缺省值,而且要保证传的参数id和之前的id是一样的,避免出现改变id的问题.
<!-- 批量更新第三种方法,通过 replace into -->
<update id="updateBatch3" parameterType="java.util.List">
replace into people
(id,first_name,last_name) values
<foreach collection="list" item="item" separator=",">
(#{item.id},
#{item.firstName},
#{item.lastName})
</foreach>
</update>
第五种 insert into on duplicate key update
update重复记录,不会改变其它字段 ,这在我的csdn有详细介绍.
<!-- 批量更新第四种方法,通过 duplicate key update -->
<update id="updateBatch4" parameterType="java.util.List">
insert into people
(id,first_name,last_name) values
<foreach collection="list" index="index" item="item" separator=",">
(#{item.id},
#{item.firstName},
#{item.lastName})
</foreach>
ON DUPLICATE KEY UPDATE
id=values(id),first_name=values(first_name),last_name=values(last_name)
</update>
第6种 创建临时表,先更新临时表,然后从临时表中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;
(这个我没试,这个可以后面单独研究,它的效率和replace into 差不多)
foreach效率其实相当高的,因为它仅仅有一个循环体,只不过最后update语句比较多,量大了就有可能造成sql阻塞。
case when虽然最后只会有一条更新语句,但是xml中的循环体有点多,每一个case when 都要循环一遍list集合,所以大批量拼sql的时候会比较慢,所以效率问题严重。使用的时候建议分批插入。
insert into on duplicate key update可以看出来是最快的,但是一般大公司都禁用,
公司一般都禁止使用replace into和INSERT INTO … ON DUPLICATE KEY UPDATE,这种sql有可能会造成数据丢失和主从上表的自增id值不一致。而且用这个更新时,记得一定要加上id.
更多推荐
所有评论(0)