如何插入记录或更新(如果已存在)? [英] How to INSERT a record or UPDATE if it already exists?
问题描述
我有一个表,其中包含列record_id
(汽车公司),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 supports the insert-on-duplicate syntax, f.e.:
INSERT INTO table (key,col1) VALUES (1,2)
ON DUPLICATE KEY UPDATE col1 = 2;
这篇关于如何插入记录或更新(如果已存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!