欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

insert into … on duplicate key update / replace into 多行数_MySQL

程序员文章站 2022-06-17 16:41:48
...
bitsCN.com

场景是这样的,我有KV型的表,建表语句如下:


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

数据大概是这样的:

+----+----+-----------+
| 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 |
+----+----+-----------+

当我插入一条数据时,我要判断(k1,k2)是否已经存在(1条selete),若存在就update,不存在就insert,这是一个典型的merge过程,虽然按照PK执行操作的速度非常快,但是毕竟SQL交互量上去了,如果我有100笔这样的SQL,那这个开销是很可观的,有没有什么一条SQL就能搞定的事情呢?

有两种写法:

第一种: 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);

第二种 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');

最终都能将数据改成这样:


+----+----+-----------+
| 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 |
+----+----+-----------+

bitsCN.com