mysql更换主键遇到的一个问题

关于主键的SQL语法:
alter table t_google_mem drop primary key; //删除表现有主键
alter table t_google_mem add primary key (f_id); //创建主键
alter table t_google_mem add primary key (f_id, f_csname); //创建多值主键

下面说下我在实际的工作过程中,遇到的一个问题。目前我有了如下的一张表,现在要做的操作是将f_id和f_csname联合作为多值主键。

mysql> desc t_google_mem;
+--------------+-----------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-----------+------+-----+---------------------+----------------+
| f_id | int(10) | NO | PRI | NULL | auto_increment |
| f_name | char(255) | NO | | | |
| f_assion | char(255) | NO | | | |
| f_csname | char(255) | NO | | | |
| f_time | datetime | NO | | 0000-00-00 00:00:00 | |
| f_status | int(10) | NO | | 1 | |
+--------------+-----------+------+-----+---------------------+----------------+

错误的做法:
按照以前的习惯,我的打算是先删除掉表的主键,然后再添加多值主键。但在使用alter table t_google_mem drop primary key;语句时,出错了提示如下:
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
错误的大概意思是:不正确的表格定义;这里只能有一个字段当作auto increment,并且必须把这个字段作为主键。

思考上面的错误提示后,我觉得正确的步骤应该首先去掉表中字段f_id的auto_increment的属性,然后再删除主键,下一步再添加多值主键,最后再将f_id调整成auto_increment。

说做就做,下面开始实施SQL修改。
第一步:alter table t_google_mem modify f_id int(10) not null default 0;

mysql> alter table t_google_mem modify f_id int(10) not null default 0;
Query OK, 41 rows affected (0.05 sec)
Records: 41 Duplicates: 0 Warnings: 0

第二步:alter table t_google_mem drop primary key;

mysql> alter table t_google_mem drop primary key;
Query OK, 41 rows affected (0.04 sec)
Records: 41 Duplicates: 0 Warnings: 0

第三步:alter table t_google_mem add primary key (f_id, f_csname);

mysql> alter table t_google_mem add primary key (f_id, f_csname);
Query OK, 41 rows affected (0.03 sec)
Records: 41 Duplicates: 0 Warnings: 0

第四步:alter table t_google_mem modify f_id int(10) not null auto_increment;

mysql> alter table t_google_mem modify f_id int(10) not null auto_increment;
Query OK, 41 rows affected (0.02 sec)
Records: 41 Duplicates: 0 Warnings: 0

经过上述4步的修改后,检查表结构,结果显示已经满足我的要求。

mysql> desc t_google_mem;
+--------------+-----------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-----------+------+-----+---------------------+----------------+
| f_id | int(10) | NO | PRI | NULL | auto_increment |
| f_name | char(255) | NO | | | |
| f_assion | char(255) | NO | | | |
| f_csname | char(255) | NO | PRI | | |
| f_time | datetime | NO | | 0000-00-00 00:00:00 | |
| f_status | int(10) | NO | | 1 | |
+--------------+-----------+------+-----+---------------------+----------------+
原文地址:https://www.cnblogs.com/motadou/p/1694597.html