mysql insert or update ON DUPLICATE KEY UPDATE

CREATE TABLE `zzz` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `names` varchar(10) CHARACTER SET utf8 DEFAULT NULL,
  `kecheng` varchar(80) CHARACTER SET utf8mb4 NOT NULL COMMENT 'course',
  `score` int(11) DEFAULT NULL COMMENT 'score',
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx` (`names`,`kecheng`)
) ENGINE=InnoDB;

insert into `zzz` (`id`, `names`, `kecheng`, `score`) values('1','a','language','80');
insert into `zzz` (`id`, `names`, `kecheng`, `score`) values('2','b','language','85');
insert into `zzz` (`id`, `names`, `kecheng`, `score`) values('3','a','math','90');
insert into `zzz` (`id`, `names`, `kecheng`, `score`) values('4','b','math','77');
insert into `zzz` (`id`, `names`, `kecheng`, `score`) values('5','a','English','80');
insert into `zzz` (`id`, `names`, `kecheng`, `score`) values('6','b','English','88');


Names and kecheng have established a unique index, so an error will be reported when repeating records with names and kecheng repeating at the same time. At this time, if you want to update the score, you can write as follows:
insert into zzz(names,kecheng,score) values('a','语文',10) on duplicate key update score=90;

1 queries executed, 1 success, 0 errors, 0 warnings

Query: insert into zzz(names,kecheng,score) values('a','language',10) on duplicate key update score=90

2 rows affected

Execution time: 0.056 sec
Transmission time: 0 sec
Total time: 0.056 sec


2 rows are affected, first try to insert, the insertion is unsuccessful, then the unsuccessful data is deleted, and then the modification is performed, which is equivalent to one deletion and one update, so 2
rows are affected.
At 6, after executing this sql, execute the normal insert (non-duplicate data), and find that the id is 8 instead of 7, indicating that 7 has been used, but the data of 7 was unsuccessfully inserted and deleted.


What if there is duplicate data, but you don't want to update any fields? For
example, the duplicate data is ignored directly and the score field is not updated, you can do this:
INSERT INTO zzz(NAMES,kecheng,score) VALUES('a','语文',10) ON DUPLICATE KEY UPDATE score=score;

1 queries executed, 1 success, 0 errors, 0 warnings

Query: insert into zzz(names,kecheng,score) values('a','language',10) on duplicate key update score=score

0 rows affected

Execution time: 0.049 sec
Transmission time: 0 sec
Total time: 0.049 sec

Affected 0 rows, indicating that there is no change.


If there is duplicate data, what about updating multiple fields?
INSERT INTO zzz(NAMES,kecheng,score) VALUES('a','语文',10) ON DUPLICATE KEY UPDATE score=score,kecheng=kecheng;

1 queries executed, 1 success, 0 errors, 0 warnings

Query: insert into zzz(names,kecheng,score) values('a','language',10) on duplicate key update score=score

0 rows affected

Execution time: 0.049 sec
Transmission time: 0 sec
Total time: 0.049 sec

Guess you like

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