基本使用类 自增主键达到上限,无法插入数据 场景描述 插入数据时报错ERROR 1062 (23000): Duplicate entry 'xxx' for key 'xxx'。 原因分析 自增主键的字段取值达到上限,无法继续增长,导致新插入的数据生成的自增主键值与表中上一条数据相同,因为自增主键的值不可重复,插入失败报错。 解决方案 1. 如果数据变化较多,表中实际数据量远小于自增主键的容量,则可以考虑将该表的数据全量导入新表,删除原表,然后rename将新表名改回原表名。(使用数据导入导出的方法有多种实现方法,此处仅举其中一种例子) a. 创建表autotest5tmp。 create table autotest5tmp(id tinyint not null AUTOINCREMENT, name varchar(8), PRIMARY KEY (id)); Query OK, 0 rows affected (0.07 sec) b. 插入数据。 insert into autotest5tmp select 0,name from autotest5; Query OK, 6 rows affected (0.01 sec) Records: 6 Duplicates: 0 Warnings: 0 c. 查询表数据。 select from autotest5tmp; ++ id name ++ 1 A 2 B 3 C 4 X 5 Y 6 Z ++ d. 删除表。 drop table autotest5; e. 重命名。 rename table autotest5tmp to autotest5; Query OK, 0 rows affected (0.12 sec) 2. 如果自增主键的取值范围不够,则修改自增主键的字段类型。 alter table autotest6 modify column id int NOT NULL AUTOINCREMENT; Query OK, 6 rows affected (0.15 sec) Records: 6 Duplicates: 0 Warnings: 0