MySql 批量插入

使用场景:
在需要批量插入大量的数据,判断数据是否重复。

1. insert ignore into

当插入数据时,如果出现错误时,如重复数据,将不返回错误,只是以警告的形式返回。所以在使用 ignore前请确保语句本身没有问题,否则也会被忽略掉

例如:

insert ignore into user(name) values('admin');

有可能会导致不是因为重复数据报错, 而是因为其他原因报错而被忽略掉了

2. on duplicate key update

注意:当primary 或者 unique 重复时,则执行 update 语句,如update后为无用语句。如 id = id,则同1 功能相同,但错误不会被忽略掉。

例如:
为了实现 name 重复的数据插入不报错,可以使用以下语句

insert into user(name) value('admin') on duplicate key update id = id

注意:这种方法有个前提条件,就是需要约束。主键或者唯一约束,来确保当数据重复时能根据约束来更新值。

3. insert … select … where not exist

根据select 的条件判断是否插入

insert into user(name) select 'admin' from 另外一张表 where not exists (select id from user where id = 1)

注意:这里使用的是子查询(临时表的方式),效率会有影响

4. replace into

如果存在 primary or unique 相同的记录,则先删除掉,再插入记录。

replace into user select 1,'admin' fom user

注意:不管原来有没有相同的记录,都会删除掉然后再插入

附带一下笔记:
创建索引的三种方式

1. 创建表的同时创建索引

例如:

create table user(
	id int primary key,
	name varchar(50),
	phone varchar(50),
	unique index unique_index_phone(索引名) (phone(字段名)) //唯一索引
	index index_id(id) // 普通索引
)

2. 在已经建好的表中添加索引

例如:

// 普通索引
create index 索引名 on 表名(字段名);

// 唯一索引
create unique index 索引名 on 表名(字段名);

// 全文索引
create fulltext index 索引名 on 表名(字段名)

// 多列索引,复合索引
create index 索引名 on 表名(字段1,字段2...);

3. 以修改表的方式添加索引

例如:

// 普通索引
alter table 表名 add index 索引名(字段名);

// 唯一索引
alter table 表名 add unique index 索引名(字段名);

// 全文索引
alter table 表名 add fulltext index 索引名(字段名);

查看某张表的索引:

show index from 表名;

4、duplicate key

<insert id="batchInsertOrUpdateUserStage">
        INSERT INTO user_flow_stage_info(user_gid, phone, user_stage, credit_stage, register_time, create_time, update_time,channel,sub_channel)
        values
        <foreach collection="list" item="item" index="index" separator="," >
             (#{item.userGid},#{item.phone},#{item.userStage},#{item.creditStage},#{item.registerTime},#{item.createTime},#{item.updateTime},#{item.channel},#{item.subChannel})
        </foreach>
        ON DUPLICATE KEY UPDATE user_gid = VALUES(user_gid),
        phone = VALUES(phone),
        user_stage = VALUES(user_stage),
        credit_stage = VALUES(credit_stage),
        update_time = VALUES(update_time)
    </insert>

ON DUPLICATE KEY UPDATE 可以达到以下目的:

向数据库中插入一条记录:

若该数据的主键值/ UNIQUE KEY 已经在表中存在,则执行更新操作, 即UPDATE 后面的操作。

否则插入一条新的记录。

使用注意事项!!!!
使用要点:

  1. 表要求必须有主键或唯一索引才能起效果,否则insert或update无效;

  2. 注意语法on duplicate key update后面应为需要更新字段,不需要更新的字段不用罗列;

  3. 相较于replace into(insert加强版,不存在时insert,存在时先delete后insert)虽然也能达到批量更新目的,但因为删除和添加需要重复维护索引,所以大批量比on duplicate key update性能要差,小量可忽略,自选为主。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐