1.insert into values、insert into select
INSERT INTO t
VALUES
(1, 20, 'a'),
(2, 26, 'b');
-- 两张表的字段要一一对应
INSERT INTO t
SELECT * from t_copy where id = 1;
注:insert into values 或 insert into select批量插入时,都满足事务的原子性与一致性,一条出错整体都会回滚。在使用insert into select时,MySQL会对select的数据加S(读)锁,在事务较为复杂的场景下可能有死锁的风险
2.replace into
replace into表示插入替换数据,当记录中有PrimaryKey,或者unique索引的话,如果数据库已经存在数据,则用新数据替换(先delete再insert),如果没有数据效果则和insert into一样。
REPLACE INTO t (id,age) VALUES (2, 15);
3.insert into on duplicate key update
insert into on duplicate key update表示插入更新数据,当记录中有PrimaryKey,或者unique索引的话,如果数据库已经存在数据,则用新数据更新(update),如果没有数据效果则和insert into一样。
INSERT INTO t
(id, age)
VALUES
(3, 28),
(4, 29)
ON DUPLICATE KEY UPDATE
id = VALUES(id),
age = VALUES(age);
4.insert ignore into
insert ignore into表示尽可能的忽略冲突
INSERT IGNORE INTO t VALUES(1,30,'f'),(6,33,'o');
总结
1.insert into values 或 insert into select批量插入时,都满足事务的原子性与一致性,但要注意insert into select的加锁问题。
2.replace into与insert into on duplicate key update都可以实现批量的插入更新,具体是更新还是插入取决与记录中的pk或uk数据在表中是否存在。如果存在,前者是先delete后insert,后者是update。
3.insert ignore into会忽略很多数据上的冲突与约束,平时很少使用。