insert into... on duplicate key update and replace into multi line data introduction

  • 2020-05-30 21:11:37
  • OfStack

The scene is like this. I have an KV table. The sentences are as follows:


CREATE TABLE `dkv` ( 
  `k1` int(11) NOT NULL DEFAULT '0', 
  `k2` int(11) NOT NULL DEFAULT '0', 
  `val` varchar(30) DEFAULT NULL, 
  PRIMARY KEY (`k1`,`k2`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8

The data looks something like this:

+----+----+-----------+
| k1 | k2 | val |
+----+----+-----------+
| 1 | 1 | value 1-1 |
| 1 | 2 | value 1-1 |
| 1 | 3 | value 1-1 |
| 1 | 5 | value 1-1 |
| 1 | 7 | value 1-1 |
+----+----+-----------+

When I insert 1 the data, I want to determine whether (k1 k2) already exists (article 1 selete), if any update, insert does not exist, this is a typical merge process, although the implementation is PK operation speed is very fast, but after all SQL interaction volume up, if I had 100 such SQL, that this overhead is very handsome, is there any article 1 SQL about what can be done?

There are two ways to write it:

Type 1: insert into... on duplicate key update


insert DELAYED into dkv  
values 
(1,2,'new 12a'), 
(1,3,'new 33ba'), 
(1,4,'new 23222'), 
(1,6,'new 12333'), 
(1,8,'new vaaaa'), 
(1,20,'new vaff'), 
(1,25,'new vaff') 
ON DUPLICATE KEY UPDATE val=VALUES(val);

The second replace into:


replace into dkv  
values 
(1,2,'new 12a'), 
(1,3,'new 33ba'), 
(1,4,'new 23222'), 
(1,6,'new 12333'), 
(1,8,'new vaaaa'), 
(1,20,'new vaff'), 
(1,25,'new vaff');

You can eventually change the data to something like this:


+----+----+-----------+ 
| k1 | k2 | val       | 
+----+----+-----------+ 
|  1 |  1 | value 1-1 | 
|  1 |  2 | new 12a   | 
|  1 |  3 | new 33ba  | 
|  1 |  4 | new 23222 | 
|  1 |  5 | value 1-1 | 
|  1 |  6 | new 12333 | 
|  1 |  7 | value 1-1 | 
|  1 |  8 | new vaaaa | 
|  1 | 20 | new vaff  | 
|  1 | 25 | new vaff  | 
+----+----+-----------+


Related articles: