文档首页/ 云数据库 GaussDB(for MySQL)/ 故障排除/ 基本使用类/ 自增主键达到上限,无法插入数据
更新时间:2023-08-31 GMT+08:00
分享

自增主键达到上限,无法插入数据

场景描述

插入数据时报错 ERROR 1062 (23000): Duplicate entry 'xxx' for key 'xxx'。

原因分析

自增主键的字段取值达到上限,无法继续增长,导致新插入的数据生成的自增主键值与表中上一条数据相同,因为自增主键的值不可重复,插入失败报错。

解决方案

  1. 如果数据变化较多,表中实际数据量远小于自增主键的容量,则可以考虑将该表的数据全量导入新表,删除原表,然后rename将新表名改回原表名。(使用数据导入导出的方法有多种实现方法,此处仅举其中一种例子)
    1. 创建表auto_test5_tmp。
      create table auto_test5_tmp(id tinyint not null AUTO_INCREMENT, name varchar(8), PRIMARY KEY (`id`)); 
      Query OK, 0 rows affected (0.07 sec) 
    2. 插入数据。
      insert into auto_test5_tmp select 0,name from auto_test5; 
      Query OK, 6 rows affected (0.01 sec) 
      Records: 6  Duplicates: 0  Warnings: 0 
    3. 查询表数据。
      select * from auto_test5_tmp; 
      +----+------+ 
      | id | name | 
      +----+------+ 
      |  1 | A    | 
      |  2 | B    | 
      |  3 | C    | 
      |  4 | X    | 
      |  5 | Y    | 
      |  6 | Z    | 
      +----+------+ 
    4. 删除表。
      drop table auto_test5; 
    5. 重命名。
      rename table auto_test5_tmp to auto_test5;
      Query OK, 0 rows affected (0.12 sec)  
  2. 如果自增主键的取值范围不够,则修改自增主键的字段类型。
    alter table auto_test6  modify column id int NOT NULL AUTO_INCREMENT; 
    Query OK, 6 rows affected (0.15 sec) 
    Records: 6  Duplicates: 0  Warnings: 0  

相关文档