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。这样可以大大提高效率。

参考

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

猜你喜欢

转载自www.cnblogs.com/lanyangsh/p/8974669.html