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;
INSERT INTO mRowUpdate(id,`value`) VALUES(3, 'SuperMan') ON DUPLICATE KEY UPDATE `value`='SuperMan';
INSERT INTO `table` (`a`, `b`, `c`) VALUES (1, 2, 3), (4, 5, 6) ON DUPLICATE KEY UPDATE `c`=VALUES(`a`)+VALUES(`b`);
create table test( id int not null primary key , num int not null UNIQUE key , time int not null )
insert into test values(1,1,1), (2,2,2);
insert into test values(1,2,3) on duplicate key update tid = tid + 1;