批量插入防止重复方案整理

批量插入防止重复方案

除了在程序中处理的方案,本次共有4种方案:

1.insert ignore into

insert ignore into user (id , name) values ('1' , 'Tom' ); 

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

2.on duplicate key update

insert into user (id , name) values ('1' , 'Tom') on duplicate key update id = id

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

3.insert … select … where not exist

INSERT INTO user (id , name) values ('1'  , 'Tom') select 'id' from dual where not exists (SELECT id FROM user WHERE id = 1)

使用mysql的一个临时表的方式,里面使用到了子查询,效率也会有影响,不建议使用。

4.replace into

REPLACE INTO user SELECT 1, 'telami' FROM books

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

posted @ 2023-03-05 13:09  maoxianww  阅读(123)  评论(0编辑  收藏  举报