insert into … on duplicate key update / replace into 多行數據引見。本站提示廣大學習愛好者:(insert into … on duplicate key update / replace into 多行數據引見)文章只能為提供參考,不一定能成為您想要的結果。以下是insert into … on duplicate key update / replace into 多行數據引見正文
場景是如許的,我有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 |
+----+----+-----------+