mysql取消主键_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取消主键_mysql如何删除主键?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多个数据文件 mysql_mysql多实
- 下一篇: IDEA通过Database连接MySq