如果已经存在,如何插入记录或更新?
我有一张表,其中包含 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;
相关文章