当前位置:网站首页>on duplicate key update
on duplicate key update
2022-08-09 09:11:00 【Hu lotte】
1.语法:
insert into 表名(字段名1,字段名2,字段名3,字段名4……)
values(字段1的值,字段2的值,字段3的值,字段4的值……)
on duplicate key update 某字段=某字段的值,某字段=某字段的值,某字段=某字段的值
例如:
-- id为主键,school_code为唯一约束
-- id使用的是uuid,一般不会重复
-- If the school code column does not existnanshan,则插入该数据
-- 如果存在nanshanThis school code,Replace the school address with ‘东海’
insert into school(id,school_code,school_address)
values(UUID(),'nanshan','月亮湾')
on duplicate key update school_address='东海'
2.意思:
Determine whether the data exists in the table(存在规则:primary key 和 unique key),如果不存在则插入一条,如果存在则update该条数据.
3.注意:
1.If inserting a piece of data 主键 和 Unique data exists in the table,However, the data determined by the primary key and the data determined by the uniqueness are not the same(实际上,This occurs because there is a problem with the inserted data,We just assume this is the case),此时,updateThe data of the primary key is the one determined in the uniqueness?
After the experiment,The one for the primary key.
2.If the implementation isinsert语句,则返回的结果:Affected rows:1
If the implementation isupdate语句,则返回的结果为:Affected rows: 0 或者 Affected rows: 2
即使是update,That should affect it0line or line,为啥出来个2呢.Refer to the official explanation here
https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
Red area translation:
如果是insert则为1;
如果是update,但是updateThe content is consistent with the original data0,It is inconsistent with the original data2;
So the number of rows affected here just represents what operation was performed.
3.也有人这样写
insert ignore into ed_auth(phone_open_id,diagnostician_uid,name,school_code,id)
values(?,?,?,?,?)
on duplicate key update phone_open_id=?,name=?,school_code=?
This compares to the syntax above,在insert后面多了一个ignore,Actually this is a separate syntax(update中也可以使用),ignoreis intended to be ignored,Here it is to ignore errors,That is, when an insertion error occurs(是数据错误,不是SQL语法错误),不报错,只是返回Affected rows: 0 .
边栏推荐
猜你喜欢
VNCTF2021 部分题目复现
VoLTE基础自学系列 | IMS的业务触发机制
Failed to mount component: template or render function not defined.
canal工作原理及简单案例演示
PoPW代币分配机制或将点燃下一个牛市
BUUCTF MISC刷题笔记(二)
全球19级谷歌卫星地图免费查看下载
The difference between big-endian and little-endian storage is easy to understand at a glance
运行flutter项目时遇到的问题修改flutter为国内镜像
[漏洞复现]CVE-2018-7490(路径遍历)
随机推荐
100句话,是否会触动你?
【培训课程专用】CA/TA调用模型-代码导读
全球19级谷歌卫星地图免费查看下载
[Vulnerability reproduction] CVE-2018-7490 (path traversal)
基于蓝牙定位功能开发的医院智能导航系统
基于 JSch 实现服务的自定义监控解决方案
NodeMCU(ESP8266) 接入阿里云物联网平台 踩坑之旅
BUUCTF MISC刷题笔记(二)
[V&N2020 公开赛]内存取证
往二维数组追加键值
MySQL查漏补缺(四)存储过程和游标
代码导读-目录
按字节方式和字符方式读取文件_加载配置文件
Redis基础
SQL server中的数据类型
PoPW代币分配机制或将点燃下一个牛市
epoll LT和ET 问题总结
jfinal加载配置文件原理
TypeScript简记(一)
canal工作原理及简单案例演示