话不多说,直接进入主题
我们经常使用insert进行插入数据,但是当表中数据主键存在时,插入就会报错,所以我们会想到使用replace来进行插入数据,当数据不存在时插入,存在时更新,这样确实可以解决插入失败的问题,不过效率不高,接下来我来说三种插入方式
- insert
示例:
-- 根据数据值插入
insert into test(id, name) values(1, 'zhang');
-- 从另外一张表插入
insert into test select id, name from tmp;
这是最常用的插入数据方式,当插入数据主键有相同时,会报错
- replace
示例:
-- 根据数据插入更新
replace into test(id, name) values(1, 'zhang'), (2, 'san');
-- 根据数据插入更新
replace into test set id=1, name='zhang';
这种方式可以解决insert插入失败的问题,当主键存在时会更新,不会报错,不过效率不高
- insert ... on duplicate key update ...
insert into test(id,name)
select id, name from tmp
on duplicate key update id=values(id), name=values(name);
insert into test(id, name)
select id, name from tmp
on duplicate key update
id=case when (@time_condition :=true and values(id) > test.id)
then values(id) else test.id,
name=case when @time_condition
then values(name) else test.name;
这种方式会判断是否存在主键冲突,存在就更新,不存在冲突则直接插入,这样就解决了插入失败的问题,同时提高了插入效率