Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีลบ Primary Key ใน MySQL

สร้างตารางพร้อม Primary Key

mysql> create table PrimaryKeyDemo (
    -> id int not null,
    -> Primary key(id)
    -> );
Query OK, 0 rows affected (0.60 sec)

ตรวจสอบโครงสร้าง

mysql> desc PrimaryKeyDemo;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.06 sec)

คำสั่งลบ Primary Key

ALTER TABLE yourTableName DROP PRIMARY KEY;

นำไปใช้งาน

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

ตรวจสอบอีกครั้ง

mysql> DESC PrimaryKeyDemo;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

คอลัมน์ Key ว่างเปล่า แสดงว่า Primary Key ถูกลบเรียบร้อยแล้ว

ข้อควรระวัง: หากตารางมี Foreign Key อ้างอิง Primary Key นี้ ต้องลบ Foreign Key ก่อน