I need to write a MySQL query for insert or update some fields. I've seen about the ON DUPLICATE KEY
, but my fields are not PRIMARY KEY
or UNIQUE
, only the combination is unique. Here is the fields list:
ID (PRIMARY KEY AUTOINCREMENT BIGINT), user (BIGINT), creator (BIGINT), type (TINYINT), value (BIGINT), date (INT), readed (TINYINT), erased (TINYINT).
The table name is notifications (if it can be useful). I need to insert a new record or update the existent one if the user, creator, type, values are all the same of the values to insert (so like AND
). How I can do that?
You can create a unique index on the variable. I'm not sure which are the variables in question, but here is an example:
create unique index idx_table_user_creator_type on table(user, creator, type)
You can also do this in the create table
statement as well, using the syntax for a unique
constraint.
You would then use the constraint as:
insert into table(user, creator, type, col1, . . .)
values(@user, @creator, @type, . . .)
on duplicate key update col1 = values(col1),
col2 = values(col2),
. . . ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.