insert into on duplicate key update

时间:2023-03-08 23:44:29
insert into on duplicate key update

问题

有一个表,建表语句如下:

CREATE TABLE `tbl_host` (
`id` bigint(64) NOT NULL AUTO_INCREMENT,
`ip` varchar(255) NOT NULL DEFAULT '',
`host_name` varchar(2555) NOT NULL DEFAULT '',
`timestamp` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_ip` (`ip`)
) ENGINE=InnoDB AUTO_INCREMENT=84689426 DEFAULT CHARSET=utf8;

其中,

  • id为主键,自增字段
  • ip字段为唯一键

插入和更新表时使用sql语句:

insert into tbl_host(ip, host_name, timestamp) values ('%s', '%s', '%d') on duplicate key update host_name='%s', timestamp='%d'

当频繁update表记录时,通过

mysql> show create table tbl_host

发现AUTO_INCREMENT在不断增加。开始疑惑所使用的sql语句是不是有问题。

mysql官网给出说明:

With an auto-increment column, an INSERT statement increases the auto-increment value but UPDATE does not.

具体到INSERT ON DUPLICATE KEY UPDATE,即使最终执行了 update,自增ID也是会增长的。

如果id持续增长,会不会越界呢?对于int64数据类型,每分钟10w条记录更新,1亿年都消耗不完。所以,对于越界问题,可以放心使用。

建议

当遇到对表的操作是insert少, 需要大量update的情况,不建议使用insert into on duplicate key update。那如何处理情况呢?

  • 可以首先select,如果查到则update,否则insert。
  • 或者可以首先update,如果不存在,再insert。由于insert插入操作量少,大部分都是update,因此效率相对于前一种更好。具体代码可参考Go sql insert update使用举例

参考

mysql官网

https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

statckoverflow

https://*.com/questions/23516958/on-duplicate-key-auto-increment-issue-mysql

mysql的AUTO_INCREMENT如果达到最大值会怎样呢?

https://blog.csdn.net/stpeace/article/details/78066262