ALTER TABLE causes auto_increment resulting key 'PRIMARY'

修改表为主键的自动增长值时,报出以下错误:
mysql> ALTER TABLE YOON CHANGE COLUMN id id INT(11) NOT NULL AUTO_INCREMENT ADD PRIMARY KEY (id);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ADD PRIMARY KEY (id)' at line 1


解决:
将ID值为0的那条记录或其他大于0且不重复的数据;

查询重复数据:
mysql> select id,count(*) as count from yoon group by id having count > 1;
+------+-------+
| id   | count |
+------+-------+
|    1 |     2 |
+------+-------+
1 row in set (0.00 sec)


mysql> select * from yoon where id =1;
+------+------+
| id   | name |
+------+------+
|    1 | AAAA |
|    1 | DDDD |
+------+------+
2 rows in set (0.00 sec)


mysql> delete from yoon where name='DDDD';
Query OK, 1 row affected (0.00 sec)


添加表为主键的自动增长值时,依旧报出以下错误:
mysql> ALTER TABLE YOON CHANGE COLUMN id id INT(11) NOT NULL AUTO_INCREMENT ADD PRIMARY KEY (id);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ADD PRIMARY KEY (id)' at line 1

原因:
很多人都忽略了NULL值:
mysql> select * from yoon where id is null;  
+------+------+
| id   | name |
+------+------+
| NULL | EEEE |
+------+------+
1 row in set (0.00 sec)


mysql> delete from yoon where id is null;
Query OK, 1 row affected (0.01 sec)


mysql> alter table yoon change column id id int(11) not null auto_increment,add primary key(id);
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

or

alter table yoon modify id int(11) not null auto_increment primary key;

posted @   __Yoon  阅读(340)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示