mysql insert 存在即不插入语法说明
作者:954L 时间:2024-01-17 18:46:05
insert 存在即不插入语法
介绍三种方式
第一种:replace into
replace into table(id, name) values(1, '张三') ;
/*或者*/
replace into table(id, name) select 1, '张三' ;
replace into 跟 insert 功能类似。
不同点在于:replace into 首先尝试插入数据到表中
1.如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。
2.否则,直接插入新数据。
要注意的是:插入数据的表必须有主键或者是唯一索引!
否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。
第二种:DUAL临时表
insert into table(id, name)
select null, '张三' from DUAL
where not exists (select id from table where name = '张三') ;
其中的 DUAL 是一个临时表,不需要物理创建,直接用即可。
这种就不需要上述那种必须主键相同或者有唯一索引的字段。
第三种:根据主键判断
insert into table(id, name) on duplicate key update name = '李四';
根据主键id进行判重。
效果区别
第一种:不存在即插入,存在即修改
第二种:不存在即插入,存在则不做处理
第三种:不存在不做处理,存在即执行update
已有数据存在则不插入,否则则修改
经常遇到这样的情景,向一个表里插入一条数据,如果已经存在就更新一下,用程序实现麻烦而且在并发的时候可能会有问题,这时用mysql的DUPLICATE KEY 很方便
用法
INSERT INTO agent_user (group_id,group_type,user_name, user_mobile,created_time,updated_time)
SELECT 9503,8,a.user_name,a.user_mobile,1642397508000,1642397508000
from agent_user_heimingdan a on DUPLICATE KEY UPDATE user_mobile = a.user_mobile;
来源:https://blog.csdn.net/wkh___/article/details/82856801
标签:mysql,insert,存在,不插入
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python+matplotlib实现简单曲线的绘制
2023-01-05 17:21:27
![](https://img.aspxhome.com/file/2023/2/78492_0s.png)
python得到windows自启动列表的方法
2023-12-18 14:49:13
指导:SQL Server无日志恢复数据库
2009-02-20 17:07:00
golang如何优雅的编写事务代码示例
2024-05-28 15:23:43
![](https://img.aspxhome.com/file/2023/4/123884_0s.jpg)
Python设计模式之组合模式原理与用法实例分析
2023-04-12 16:15:28
![](https://img.aspxhome.com/file/2023/3/95563_0s.png)
使用Python获取爱奇艺电视剧弹幕数据的示例代码
2022-08-09 08:38:29
![](https://img.aspxhome.com/file/2023/3/101103_0s.png)
基于Python生成个性二维码过程详解
2021-08-05 13:04:38
![](https://img.aspxhome.com/file/2023/6/69456_0s.png)
Python如何截图保存的三种方法(小结)
2023-08-24 22:17:19
![](https://img.aspxhome.com/file/2023/2/62592_0s.png)
Django中的DateTimeField和DateField实现
2021-02-03 20:38:13
![](https://img.aspxhome.com/file/2023/0/134790_0s.png)
python装饰器代码深入讲解
2023-08-17 20:59:19
asp 删除数据并同时删除图片的代码
2011-02-28 10:39:00
Python中异常重试的解决方案详解
2021-06-16 01:12:24
Python time模块之时间戳与结构化时间的使用
2024-01-02 09:07:51
![](https://img.aspxhome.com/file/2023/3/66383_0s.png)
python中正则表达式的使用详解
2023-08-08 14:47:13
![](https://img.aspxhome.com/file/2023/5/62285_0s.png)
Python数据分析之使用scikit-learn构建模型
2023-11-10 23:19:10
![](https://img.aspxhome.com/file/2023/5/64365_0s.jpg)
python 函数、变量中单下划线和双下划线的区别详解
2021-06-29 11:32:33
python里的条件语句和循环语句你了解多少
2022-07-19 02:27:49
![](https://img.aspxhome.com/file/2023/6/107616_0s.gif)
浅析Go语言中闭包的使用
2024-02-16 12:35:18
![](https://img.aspxhome.com/file/2023/3/113103_0s.png)
python 3.7.0 安装配置方法图文教程
2023-10-14 22:24:28
![](https://img.aspxhome.com/file/2023/2/65522_0s.jpg)
windows安装TensorFlow和Keras遇到的问题及其解决方法
2022-04-04 02:14:23
![](https://img.aspxhome.com/file/2023/3/67803_0s.png)