How to INSERT a record or UPDATE if it already exists?(如果已经存在,如何插入记录或更新?)
问题描述
我有一张表,其中包含 record_id
(auto inc)、sender
、sent_time
和 status
列.
I have a table with columns record_id
(auto inc), sender
, sent_time
and status
.
如果没有特定发件人的任何记录,例如sender1",我必须插入一条新记录,否则我必须更新属于user1"的现有记录.
In case there isn't any record of a particular sender, for example "sender1", I have to INSERT a new record otherwise I have to UPDATE the existing record which belongs to "user1".
所以如果没有任何记录已经存储,我会执行
So if there isn't any record already stored, I would execute
# record_id is AUTO_INCREMENT field
INSERT INTO messages (sender, sent_time, status)
VALUES (@sender, time, @status)
否则我会执行 UPDATE 语句.
Otherwise I would execute UPDATE statement.
无论如何.. 如果没有字段发件人值为user1"的任何记录,是否有人知道如何组合这两个语句以插入新记录,否则更新现有记录?
Anyway.. does anyone know how to combine these two statements in order to insert a new record if there isn't any record where the field sender value is "user1" otherwise update the existing record?
推荐答案
MySQL支持insert-on-duplicate 语法,fe:
MySQL supports the insert-on-duplicate syntax, f.e.:
INSERT INTO table (key,col1) VALUES (1,2)
ON DUPLICATE KEY UPDATE col1 = 2;
这篇关于如果已经存在,如何插入记录或更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果已经存在,如何插入记录或更新?


- 更改自动增量起始编号? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- SQL 临时表问题 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01