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

วิธีเพิ่ม AUTO_INCREMENT ให้คอลัมน์ที่มีอยู่แล้วด้วย ALTER TABLE

คำสั่ง

ALTER TABLE yourTableName CHANGE yourColumnName yourColumnName dataType AUTO_INCREMENT PRIMARY KEY;

ตัวอย่าง

สร้างตาราง (ยังไม่มี PK, ไม่มี AI)

mysql> create table AlterTableToAddAutoIncrement (StudentId int);

เพิ่ม AUTO_INCREMENT + PRIMARY KEY พร้อมกัน

mysql> alter table AlterTableToAddAutoIncrement change StudentId StudentId int AUTO_INCREMENT Primary key;
Query OK, 0 rows affected (1.93 sec)

ทดสอบ Insert ไม่ระบุค่า

mysql> insert into AlterTableToAddAutoIncrement values();
mysql> insert into AlterTableToAddAutoIncrement values();
mysql> insert into AlterTableToAddAutoIncrement values();

ผลลัพธ์

mysql> select * from AlterTableToAddAutoIncrement;
+-----------+
| StudentId |
+-----------+
| 1         |
| 2         |
| 3         |
+-----------+

สรุป

  • ใช้ CHANGE (ไม่ใช่ MODIFY) เมื่อต้องการเปลี่ยนชื่อคอลัมน์หรือเพิ่ม PRIMARY KEY พร้อมกัน
  • ถ้ามี PRIMARY Key อยู่แล้ว ให้ DROP PK ก่อน แล้วค่อย ADD PK ใหม่พร้อม AI
  • คอลัมน์ AI ต้องเป็น NOT NULL (เพิ่มอัตโนมัติ)