MySQL – Insert Update On Duplicate Key Update

Insert a record into the database. If the primary key value (UNIQUE KEY) of the data already exists in the table, perform the following UPDATE operation. Otherwise, perform the previous INSERT operation.

Test table structure

CREATE < span style="color: #0000ff;">TABLE `flume_meta` (

`source_tab`
varchar(255) COLLATE utf8_bin DEFAULT NULL UNIQUE,
`current_index`
bigint(255) DEFAULT NULL
) ENGINE
=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Share pictures

Perform update insert

INSERT INTO `flume_meta` VALUES('user',1)

ON DUPLICATE KEY
UPDATE source_tab='user',current_index=5;

After the first execution< /p>

Share picture

Execute again

Share a picture

It has become an update operation

CREATE TABLE `flume_meta` (

`source_tab`
varchar(255) COLLATE utf8_bin DEFAULT NULL UNIQUE,
`current_index`
bigint(255) DEFAULT NULL
) ENGINE
=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

INSERT INTO `flume_meta` VALUES( 'user',1)

ON DUPLICATE KEY
UPDATE source_tab='user',current_index=5;

Leave a Comment

Your email address will not be published.