浅析MySQL replace into 的用法
时间:2024-01-18 15:58:38
在 SQL Server 中可以这样处理:
if not exists (select 1 from t where id = 1)
insert into t(id, update_time) values(1, getdate())
else
update t set update_time = getdate() where id = 1
那么 MySQL 中如何实现这样的逻辑呢?别着急!MySQL 中有更简单的方法: replace into
replace into t(id, update_time) values(1, now());
或
replace into t(id, update_time) select 1, now();
replace into 跟 insert 功能类似,不同点在于:replace into 首先尝试插入数据到表中, 1. 如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。 2. 否则,直接插入新数据。 要注意的是:插入数据的表必须有主键或者是唯一索引!否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。
MySQL replace into 有三种形式:
replace into tbl_name(col_name, ...) values(...)
replace into tbl_name(col_name, ...) select ...
replace into tbl_name set col_name=value, ...
前两种形式用的多些。其中 “into” 关键字可以省略,不过最好加上 “into”,这样意思更加直观。另外,对于那些没有给予值的列,MySQL 将自动为这些列赋上默认值。
标签:MySQL,replace,into
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SQLServer 设置单词首字母大写
2024-01-12 20:14:41
js文本框输入内容智能提示效果
2024-04-22 13:01:32
![](https://img.aspxhome.com/file/2023/4/135974_0s.jpg)
教你用Python matplotlib库制作简单的动画
2021-08-20 02:58:49
![](https://img.aspxhome.com/file/2023/2/77622_0s.gif)
Python对列表的操作知识点详解
2022-05-08 09:06:39
![](https://img.aspxhome.com/file/2023/9/82939_0s.png)
Python实现备份MySQL数据库的方法示例
2024-01-27 18:20:04
python requests库爬取豆瓣电视剧数据并保存到本地详解
2022-05-29 08:35:05
![](https://img.aspxhome.com/file/2023/0/92190_0s.png)
python益智游戏计算汉诺塔问题示例
2023-02-20 13:02:56
python缩进长度是否统一
2022-08-02 00:37:11
数据库中间件MyCat的介绍
2024-01-20 19:05:06
![](https://img.aspxhome.com/file/2023/3/67573_0s.png)
CentOS下安装Memcached和PHP Memcached扩展
2023-11-14 14:50:19
一些 T-SQL 技巧
2024-01-26 00:21:16
导致python中import错误的原因是什么
2023-08-21 05:24:04
为什么MySQL选择Repeatable Read作为默认隔离级别
2024-01-13 01:09:26
![](https://img.aspxhome.com/file/2023/6/122936_0s.jpg)
php设计模式之适配器模式实例分析【星际争霸游戏案例】
2024-05-11 09:55:05
MYSQL Binlog恢复误删数据库详解
2024-01-27 06:17:30
![](https://img.aspxhome.com/file/2023/5/129945_0s.png)
python单测框架之pytest常见用法
2021-05-22 04:13:02
![](https://img.aspxhome.com/file/2023/9/69509_0s.png)
网页设计细节不能丢
2007-09-26 11:54:00
mysql 不能插入中文问题
2024-01-26 01:19:50
用CSS实现柱状图(Bar Graph)的方法(三)——复杂柱状图的实现
2008-05-26 13:36:00
![](https://img.aspxhome.com/file/UploadPic/20085/26/2008526134946841s.jpg)
Python os模块常用方法和属性总结
2021-05-06 13:46:12