场景是这样的,我有KV型的表,建表语句如下:
复制代码 代码如下: CREATE TABLE `dkv` ( nbsp; `k1` int(11) NOT NULL DEFAULT '0', nbsp; `k2` int(11) NOT NULL DEFAULT '0', nbsp; `val` varchar(30) DEFAULT NULL, nbsp; PRIMARY KEY (`k1`,`k2`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
数据大概是这样的:
+----+----+-----------+ | k1 | k2 | valnbsp;nbsp;nbsp;nbsp;nbsp;nbsp; | +----+----+-----------+ |nbsp; 1 |nbsp; 1 | value 1-1 | |nbsp; 1 |nbsp; 2 | value 1-1 | |nbsp; 1 |nbsp; 3 | value 1-1 | |nbsp; 1 |nbsp; 5 | value 1-1 | |nbsp; 1 |nbsp; 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 dkvnbsp; 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 dkvnbsp; 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 | valnbsp;nbsp;nbsp;nbsp;nbsp;nbsp; | +----+----+-----------+ |nbsp; 1 |nbsp; 1 | value 1-1 | |nbsp; 1 |nbsp; 2 | new 12anbsp;nbsp; | |nbsp; 1 |nbsp; 3 | new 33banbsp; | |nbsp; 1 |nbsp; 4 | new 23222 | |nbsp; 1 |nbsp; 5 | value 1-1 | |nbsp; 1 |nbsp; 6 | new 12333 | |nbsp; 1 |nbsp; 7 | value 1-1 | |nbsp; 1 |nbsp; 8 | new vaaaa | |nbsp; 1 | 20 | new vaffnbsp; | |nbsp; 1 | 25 | new vaffnbsp; | +----+----+-----------+
(编辑:泉州站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|