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

เพิ่มคอลัมน์ ENUM ใหม่ในตาราง MySQL ที่มีอยู่แล้ว

เมื่อต้องการเพิ่มคอลัมน์ใหม่ที่มีชนิดข้อมูล ENUM (ค่าคงที่ที่กำหนดไว้ล่วงหน้า) ให้ใช้ ALTER TABLE ... ADD ระบุค่า ENUM ในวงเล็บ

Syntax

ALTER TABLE yourTableName ADD yourColumnName ENUM('value1','value2',...) NOT NULL;

สร้างตารางเดิม

mysql> create table DemoTable (
    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    StudentName varchar(200),
    StudentAge int
);

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

mysql> DESC DemoTable;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| StudentId   | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentName | varchar(200) | YES  |     | NULL    |                |
| StudentAge  | int(11)      | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

เพิ่มคอลัมน์ ENUM สำหรับ Gender

mysql> ALTER TABLE DemoTable ADD StudentGender ENUM('Male','Female') NOT NULL;

ตรวจสอบหลังเพิ่ม

mysql> desc DemoTable;
+---------------+-----------------------+------+-----+---------+----------------+
| Field         | Type                  | Null | Key | Default | Extra          |
+---------------+-----------------------+------+-----+---------+----------------+
| StudentId     | int(11)               | NO   | PRI | NULL    | auto_increment |
| StudentName   | varchar(200)          | YES  |     | NULL    |                |
| StudentAge    | int(11)               | YES  |     | NULL    |                |
| StudentGender | enum('Male','Female') | NO   |     | NULL    |                |
+---------------+-----------------------+------+-----+---------+----------------+

ลักษณะของ ENUM

  • เก็บได้แค่ค่าในรายการที่กำหนด
  • ภายในเก็บเป็น Integer (1, 2, 3...) ประหยัดพื้นที่
  • สูงสุด 65,535 ค่า
  • เรียงตามลำดับที่ Define (Male=1, Female=2)
  • Case Insensitive ตาม Collation

INSERT ข้อมูล ENUM

INSERT INTO DemoTable(StudentName, StudentAge, StudentGender) 
VALUES ('John', 20, 'Male'), ('Jane', 19, 'Female');

-- หรือใช้ Index (ไม่แนะนำ - อ่านยาก)
INSERT INTO DemoTable(StudentName, StudentAge, StudentGender) 
VALUES ('Bob', 21, 1); -- 1 = Male

ขยาย ENUM: เพิ่มค่าใหม่

ALTER TABLE DemoTable MODIFY StudentGender ENUM('Male','Female','Other') NOT NULL;
  • ต้องใช้ MODIFY ระบุค่าเก้าครบ + ค่าใหม่
  • ไม่สามารถลบค่าที่มีข้อมูลอยู่ได้

ENUM vs CHECK Constraint (MySQL 8.0.16+)

-- CHECK Constraint (ยืดหยุ่นกว่า, Standard SQL)
ALTER TABLE DemoTable ADD CONSTRAINT chk_gender CHECK (StudentGender IN ('Male','Female','Other'));

คำเตือน

  • ENUM เป็น MySQL Extension - ไม่ใช่ Standard SQL
  • Migration ไป DB อื่นยาก (PostgreSQL ใช้ CHECK/Type, SQL Server 用 CHECK)
  • ALTER TABLE เพิ่มค่า ENUM ต้อง Lock Table (Metadata Lock)
  • ควรพิจารณา Lookup Table (Foreign Key) แทนสำหรับ Production