• [原] 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  |
    +----+----+-----------+
  • 相关阅读:
    4.1.7 POD对象
    异常处理
    POJ3167 Cow Patterns [KMP]
    POJ1961 Period [KMP应用]
    POJ2778 DNA Sequence [AC自动机+矩阵]
    HDU2243 考研路茫茫——单词情结 [AC自动机+矩阵]
    POJ2185 Milking Grid [KMP应用]
    POJ2541 Binary Witch [状态压缩]
    ZOJ3430 Detect the Virus [AC自动机]
    POJ2752 Seek the Name, Seek the Fame [KMP]
  • 原文地址:https://www.cnblogs.com/killkill/p/2736479.html
Copyright © 2020-2023  润新知