如何在 MySQL 中删除主键?


若要删除主键,请首先使用 ALTER 来更改表。然后,使用 DROP 来删除键,如下所示

语法

alter table yourTableName drop primary key;

让我们首先创建一个表 -

mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL,
   -> StudentName varchar(20),
   -> StudentAge int,
   -> primary key(StudentId)
   -> );
Query OK, 0 rows affected (0.48 sec)

以下是对表描述的查询 -

mysql> desc DemoTable;

这将产生以下输出 -

+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| StudentId   | int(11)     | NO   | PRI | NULL    |       |
| StudentName | varchar(20) | YES  |     | NULL    |       |
| StudentAge  | int(11)     | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

以下是删除 MySQL 中主键的查询 -

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

让我们再次检查表描述 -

mysql> desc DemoTable;

这将产生以下输出 -

+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| StudentId   | int(11)     | NO   |     | NULL    |       |
| StudentName | varchar(20) | YES  |     | NULL    |       |
| StudentAge  | int(11)     | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

更新于: 18-Dec-2019

453 次浏览

开启您的职业生涯

完成本课程认证

开始学习
广告