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

วิธีเพิ่ม Composite Primary Key ด้วย ALTER TABLE ใน MySQL

สร้างตารางตัวอย่าง

mysql> create table CompositePrimaryKey (
    -> Id int,
    -> StudentName varchar(100),
    -> Age int
    -> );
Query OK, 0 rows affected (0.56 sec)

ตรวจสอบโครงสร้างเริ่มต้น

mysql> desc CompositePrimaryKey;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | YES  |     | NULL    |       |
| StudentName | varchar(100) | YES  |     | NULL    |       |
| Age         | int(11)      | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.09 sec)

เพิ่ม Composite Primary Key

mysql> ALTER table CompositePrimaryKey add primary key(Id,StudentName);
Query OK, 0 rows affected (1.26 sec)
Records: 0 Duplicates: 0 Warnings: 0

ตรวจสอบผลลัพธ์

mysql> DESC CompositePrimaryKey;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | NO   | PRI | NULL    |       |
| StudentName | varchar(100) | NO   | PRI | NULL    |       |
| Age         | int(11)      | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

คอลัมน์ Key แสดง PRI สำหรับทั้ง Id และ StudentName ยืนยันว่า Composite Primary Key ถูกเพิ่มสำเร็จ