MySQL_INSERT UPDATE ON DUPLICATE KEY UPDATE

Usually when we design database tables, we always design unique or add primary key constraints to the table.

When inserting data at this time, there is often such a situation:

We want to insert a record into the database:

  If there is a record with the same primary key in the data table, we update the record.

  Otherwise, a new record is inserted.

Logically we need to write:

$result = mysql_query('select * from xxx where id = 1');
$row = mysql_fetch_assoc($result);
if($row){
mysql_query('update ...');
}else{
mysql_query('insert ...');
}

But there are two problems with this

  • The efficiency is too poor, and 2 sql is executed each time it is executed.
  • In the case of high concurrency, there will be problems with data, and atomicity cannot be guaranteed 

Fortunately, MySQL solves this problem for us: we can achieve the above purpose through ON DUPLICATE KEY UPDATE, and can ensure the atomicity of the operation and the integrity of the data.

ON DUPLICATE KEY UPDATE can achieve the following purposes:

Insert a record into the database:

If the primary key value/UNIQUE KEY of the data already exists in the table, then perform the update operation, that is, the operation after the UPDATE; otherwise, insert a new record.

Example:

Step1 . Create a table and insert test data

SET FOREIGN_KEY_CHECKS=0;


-- ----------------------------
-- Table structure for mRowUpdate
-- ----------------------------
DROP TABLE IF EXISTS `mRowUpdate`;
CREATE TABLE `mRowUpdate` (
  `id` int(11) NOT NULL,
  `value` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;


-- ----------------------------
-- Records of mRowUpdate
-- ----------------------------
INSERT INTO `mRowUpdate` VALUES ('1', 'sss');
INSERT INTO `mRowUpdate` VALUES ('2', 'szh');
INSERT INTO `mRowUpdate` VALUES ('3', '9999');
SET FOREIGN_KEY_CHECKS=1;
Step2 . Test the usage of ON DUPLICATE KEY UPDATE:
INSERT INTO mRowUpdate(id,`value`) VALUES(3, 'SuperMan') ON DUPLICATE KEY UPDATE `value`='SuperMan';
Step3. Query data changes
 
 
=========================== Extra Story ===================== =========
Skill:
ON DUPLICATE KEY UPDATE is especially useful for multi-row inserts. Such as:
INSERT INTO `table` (`a`, `b`, `c`) VALUES (1, 2, 3), (4, 5, 6) ON DUPLICATE KEY UPDATE `c`=VALUES(`a`)+VALUES(`b`);
Tips: The VALUES() function is only meaningful in INSERT...UPDATE statements, and will return NULL otherwise.
 
Precautions:
If multiple indexes conflict, only one record is modified.
create table test(
    id int  not  null  primary  key ,
    num int  not  null  UNIQUE  key ,
    time int  not  null 
)
To test the case where both unique indexes conflict, then insert the following data
insert into test values(1,1,1), (2,2,2);
Then execute:
insert into test values(1,2,3) on duplicate key update tid = tid + 1;
Because both a and b are unique indexes, the inserted data collides with the two records, but only the first record is modified after execution

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324436073&siteId=291194637