Mysql批量插入更新

批量插入,使用MyBatis批量语法:

<insert id="insertBatch" parameterType="list">
    insert into tbl1 (a, b, c)
    values
    <foreach collection="list" item="obj" separator=",">
        (#{obj.a,jdbcType=TIMESTAMP}, #{obj.b,jdbcType=VARCHAR}, #{obj.c,jdbcType=VARCHAR})
    </foreach>
</insert>

使用临时表进行批量更新,其中的a,b作为唯一索引:

insert into tbl1  (a, b , c,d,e)
SELECT a, b ,c,d,e from tbl1_temp s 
on DUPLICATE key update c = s.c, d = s.d, e=s.e

3万条记录,第一次插入的时候1.5秒,第二次更新的时候2.5秒;

而且不会影响到该条记录的其他字段;

REPLACE into tbl1  (a, b , c,d,e)
SELECT a, b ,c,d,e from tbl1_temp s 

3万条记录,第一次插入的时候2.5秒,第二次更新的时候4.5秒;

REPLACE的时候会把记录删除重新插入,自增主键可以看出变化;

该条记录的其他字段会被清空,使用默认值填入;

原文地址:https://www.cnblogs.com/stono/p/12105832.html