如果已经存在,如何插入记录或更新?

How to INSERT a record or UPDATE if it already exists?(如果已经存在,如何插入记录或更新?)
本文介绍了如果已经存在,如何插入记录或更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表,其中包含 record_id (auto inc)、sendersent_timestatus 列.

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;

这篇关于如果已经存在,如何插入记录或更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)