如果已经存在,如何插入记录或更新? [英] How to INSERT a record or UPDATE if it already exists?

查看:33
本文介绍了如果已经存在,如何插入记录或更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表,其中包含 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;

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆