ALTER TABLE causes&nbs…

修改表为主键的自动增长值时,报出以下错误:
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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值