如何在 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 次瀏覽

開啟您的職業生涯

完成本課程認證

開始學習
廣告
© . All rights reserved.