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),我们将第一时间核实后及时予以删除。