insert into on duplicate key update

问题

有一个表,建表语句以下:html

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;

其中,mysql

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

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

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

当频繁update表记录时,经过spa

mysql> show create table tbl_host

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

mysql官网给出说明:code

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

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

若是id持续增加,会不会越界呢?对于int64数据类型,每分钟10w条记录更新,1亿年都消耗不完。因此,对于越界问题,能够放心使用。ip

建议

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

  • 能够首先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://stackoverflow.com/questions/23516958/on-duplicate-key-auto-increment-issue-mysql

mysql的AUTO_INCREMENT若是达到最大值会怎样呢? https://blog.csdn.net/stpeace/article/details/78066262

相关文章
相关标签/搜索