需求:导入excel批量插入数据库,并且校验其中数据是否存在,存在则更新,不存在则插入;
如果一条一条去校验那么效率就太慢了,少数据还好说,大数据那就不行了,所以这时就需要merge了;
解决办法:
具体步骤:
1) 新建一张和原先要插入数据表一样的表,比如原有名是xxx,再起一张临时表xxx_I好了;
2) 然后批量插入的时候插入的是xxx_I这张临时表:(我用的是mybaits)
<insert id = “insert”parameterType = “java.util.List”>
Insert into xxx_I(no,name,age)
<foreach collection = “list” item=”item”index = “index” separator=”union all”>
Select
#{item.no,jdbcType=VARCHAR}as no,
#{item.name,jdbcType=VARCHAR} as name,
#{item.age,jdbcType=VARCHAR} as age
From dual
</foreach>
</insert>
3) 接着在进行合并merge操作:
Merge into xxx target using xxx_I source on (target.no= source.no)
When not matched then insert
(no,name,name)
Values(source.no,source.name,source.age)
When matched then update set
Target.no = source.no,
Target.name =source.name,
Target.age =source.age
4) 最后在删除掉原先的临时表xxx_I数据就好了:
Delete xxx_I