当前位置: 首页 >数据库 > ALTER TABLE causes auto_increment resulting key 'PRIMARY'

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  Waings: 0

or

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

作者:__Yoon
来源链接:https://www.cnblogs.com/hankyoon/p/5169661.html

版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaclub.cn/database/117419.html

标签:SQL_syntax
分享给朋友:

“ALTER TABLE causes auto_increment resulting key 'PRIMARY'” 的相关文章

MySQL表的增删改查(进阶) 2022年05月16日 21:54:11
连接数据库版本不一致 2022年05月20日 01:07:15
MySQL 查询指定时间范围内的数据 2022年06月06日 16:59:25
MySQL学习(4)︱数据库的查询 2022年06月07日 01:52:58
mysql查询最后一条记录 2022年06月08日 19:25:45
mysql 查询列拼接字段 2022年06月12日 09:17:20
mysql查询重复的 2022年06月12日 13:49:33