場景是這樣的,我有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 |
+----+----+-----------+