我們在一個表中設置了主鍵之后,那么如何刪除主鍵呢?
刪除主鍵的語法是:
ALTER TABLE TABLE_NAME DROP PRIMARY KEY;
在這里我們要考慮兩種情況:
1、可以直接使用drop刪除主鍵的情況。
mysql> create table test1_3( -> id int not null primary key, -> name char(10) -> ); Query OK, 0 rows affected (0.01 sec) mysql> alter table test1_3 drop primary key; Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0
2、如果帶有主鍵的列還有AUTO_INCREMENT屬性,需要間接方式去掉。
mysql> create table test1_2( -> id int not null auto_increment, -> name char(10),-> primary key(id) -> ); Query OK, 0 rows affected (0.00 sec) mysql> desc test1_2;+-------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | char(10) | YES | | NULL | | +-------+----------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> desc test1_2; +-------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | char(10) | YES | | NULL | | +-------+----------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> alter table test1_2 drop primary key; ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key #這說明此列是自動增長列,無法直接刪除 mysql> alter table test1_2 modify id int; Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table test1_2 drop primary key; Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0
所以說如果列的屬性還帶有AUTO_INCREMENT,那么要先將這個列的自動增長屬性去掉,才可以刪除主鍵。