解决插入数据时,唯一索引主键冲突问题

解决插入数据时,唯一索引主键冲突问题,第1张

on duplicate key update

格式:insert into 表名(字段1,字段2)values  (值1,值2) on duplicate key update 字段=新值

作用:1、有唯一索引或主键冲突的数据插入时,只执行update后面的语句,更新指定字段的值

2、当无冲突数据插入时,就直接插入

例子:

insert into idoxu(id,stu_id,c_name) values (2,2,"huhu"),(7,7,"aha") on duplicate  key update c_name="huhu2"

执行后

replace

作用:1、有唯一索引或主键冲突的数据插入时,将删除以前的老数据,插入新的数据。如果新插入的数据中字段不全,则设为默认值,无默认值则为null(例子中istester字段,grade字段都设定了默认值为60)

2、当无冲突数据插入时,就直接插入(跟on duplicate  key update 一致)

replace into idoxu(id,stu_id,c_name) values (2,2,"huhu_replace"),(8,8,"enheng")

更新前:

执行后:

解决第16天0412作业(造数据 ,把istester表的所有数据,插入到 idoxu表)

使用on duplicate key update

insert into idoxu(id,stu_id,c_name) select id,id,uname from istester on duplicate key update c_name="new"

执行后

使用replace into

replace into idoxu(id,stu_id,c_name) select id,id,uname from istester

执行后

参考:https://www.cnblogs.com/xzwblog/p/7047849.html

一、

1.insert  into table as select from......

   insert into table(field) values()

       主键冲突:在数据插入的时候,如果主键对应的值已经存在,则插入失败,此为主键冲突。此刻可以进行选择性处理,忽略、更新或替换。

----------------------------------------------------------------------------------

        insert ignore into ......     此方法遇到主键冲突时,不更改原记录,也不报错。

2. replace into table values()  

    replace into table as select  from ......

    数据不存在则insert,若存在则replace掉,而且在列不全的情况下,未指定value的列会被设为默认值。

3. insert into table values()  on duplicate  key  update table set ..........

注意values括号里只简写一个id即可,最终生效的是update的内容。

二、关键时刻,如何使主键失效

      alter table tablename disable primary key

      alter table tablename enable primary key

      alter  table tablename drop  primary key

      使外键失效或生效:

       alter table tablenamee disable constraint  foreign_key_name


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/6754312.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-27
下一篇2023-03-27

发表评论

登录后才能评论

评论列表(0条)

    保存