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;
执行后

网友评论