批量插入并过滤数据库中已经有的数据

批量插入并过滤数据库中已经有的数据

场景: 有多条数据要插入在数据库中,并且几个字段是联合唯一索引。这个时候如果采用mybatis的batchInsert或者insertList方法,就不能通过了。同时又不能for循环需要多条数据一一判断并插入到数据库中,这种方式非常浪费资源

解决思路:利用数据库本身从A表同步数据到B表的sql,并加上not exists的判断

实例:

A表

字段名
ID
ecode
ename

B表

字段名
ID
ecode
ename

把B表中ecode不在A表中的数据导入到A表中

insert into A(ID,ecode,ename) select ID,ecode,ename from B where not exists (select ID from A where A.ecode = B.ecode)

在Mybatis实现,把集合变成一个临时表,然后采用上述的语法向表中插入数据

@Insert("<script> " +
            "insert into A(ID,ecode,ename)"+
            "select ID,ecode,ename from ("+
            "<foreach item='item' index='index' collection='dataList' separator='union all' > " +
            "( select ${item.ID} AS ID," +
            "${item.ecode} AS ecode, " +
            "'${item.ename}' AS ename FROM A "+
            "limit 1)"+
            "</foreach>"+
            ") b WHERE NOT EXISTS (SELECT * FROM A WHERE A.ecode = a.ecode)"+
            " </script> ")

注意,select常量from表 a,表中有多少条数据就会返回多少条所以加上 limit 1,使用这个方法还要确保a表中至少有一条数据,否则查询不到常量作为临时表。这个a表没有任何意义没必要与要插入的表保持一致,只要是一个确保肯定有数据的表即可

猜你喜欢

转载自blog.csdn.net/caoPengFlying/article/details/90716455