insert into … on duplicate key update / replace into 多行数_MySQL
场景是这样的,我有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 |
+----+----+-----------+
上一篇: mysql出现“Incorrect key file for table”处理方法_MySQL
下一篇: db object already connecting, open cannot be called multiple times
推荐阅读
-
Mysql中Insert into xxx on duplicate key update问题
-
mysql insert的几点操作(DELAYED,IGNORE,ON DUPLICATE KEY UPDATE )
-
mysql insert的几点操作(DELAYED,IGNORE,ON DUPLICATE KEY UPDATE )
-
mysql 中 replace into 与 insert into on duplicate key update 的用法和不同点实例分析
-
insert into … on duplicate key update / replace into 多行数_MySQL
-
mysql-mybatis 执行 INSERT … ON DUPLICATE KEY UPDATE
-
mysql-mybatis 执行 INSERT … ON DUPLICATE KEY UPDATE
-
Mysql中Insert into xxx on duplicate key update问题
-
Mysql中Insert into xxx on duplicate key update问题
-
MYSQL的REPLACE和ON DUPLICATE KEY UPDATE语句介绍解决问题实例_MySQL