首頁  >  文章  >  資料庫  >  mysql如何刪除主鍵?

mysql如何刪除主鍵?

青灯夜游
青灯夜游原創
2019-05-08 09:39:1632270瀏覽

當一個表中設定了主鍵之後,如果想要刪除主鍵了要怎麼做?以下這篇文章就跟大家介紹MySQL刪除主鍵的方法,希望對你們有幫助。

mysql如何刪除主鍵?

首先我們來看看刪除主鍵的語法:

ALTER  TABLE  TABLE_NAME  DROP  PRIMARY  KEY;

在MySQL中刪除主鍵要考慮兩種情況:

1、主鍵列不帶任何約束,可以直接刪除主鍵的情況

例:

mysql> create table test1_3(
    -> id int not null primary key,
    -> name char(10)
    -> );
Query OK, 0 rows affected (0.01 sec)

我們可以直接使用drop來刪除主鍵

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> 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               
#这说明此列是自动增长列,无法直接删除

列的屬性還帶有AUTO_INCREMENT,那麼要先將這個列的自動增長屬性去掉,才可以刪除主鍵。

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

以上是mysql如何刪除主鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn