Candidate Key ใน MySQL: การใช้ UNIQUE Constraint บนหลายคอลัมน์
Candidate Key คือคอลัมน์ (หรือชุดคอลัมน์) ที่สามารถระบุแถวได้อย่างเฉพาะเจาะจง (Unique + Not Null) — เหมาะสมเป็น Primary Key หนึ่งในหลายตัวเลือก ตัวที่เลือกเป็น Primary Key เรียกว่า Primary Key ส่วนที่เหลือคือ Alternate Keys
ไวยากรณ์: เพิ่ม UNIQUE Constraint หลายคอลัมน์
ALTER TABLE table_name
ADD UNIQUE KEY constraint_name (column1, column2);
สร้างตารางและเพิ่ม Candidate Key
mysql> create table DemoTable1400 (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(40),
-> Age int
-> );
Query OK, 0 rows affected (0.50 sec)
mysql> alter table DemoTable1400 add unique key name_age_unique(Name, Age);
Query OK, 0 rows affected (0.67 sec)
ทดสอบการทำงานของ Candidate Key
mysql> insert into DemoTable1400(Name, Age) values('Chris', 23); -- OK
mysql> insert into DemoTable1400(Name, Age) values('Chris', 23); -- ERROR 1062: Duplicate entry 'Chris-23'
mysql> insert into DemoTable1400(Name, Age) values('David', 23); -- OK (Age เดียวแต่นามสกุลต่าง)
mysql> insert into DemoTable1400(Name, Age) values('Chris', 24); -- OK (Name เดียวแต่อายุต่าง)
ข้อมูลในตาราง
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | Chris | 23 | | 4 | Chris | 24 | | 3 | David | 23 | +----+-------+------+
Candidate Key vs Primary Key
| ลักษณะ | Primary Key | Candidate Key (Alternate Key) |
|---|---|---|
| จำนวนต่อตาราง | 1 เท่านั้น | หลายตัวได้ |
| NULL | ห้ามมี NULL | ห้ามมี NULL (ในคอลัมน์ที่รวม) |
| Unique | บังคับ | บังคับ |
| Clustered Index (InnoDB) | ใช่ | ไม่ (เป็น Secondary Index) |
| Foreign Key Reference | อ้างอิงได้ | อ้างอิงได้ (MySQL รองรับ) |
เมื่อไหร่ควรใช้ Candidate Key
- มีคอลัมน์/ชุดคอลัมน์ที่ Unique โดยธรรมชาติ (เช่น Email, Passport+Country, StudentId+CourseId)
- ต้องการ enforce uniqueness แต่ไม่ใช่ primary identifier
- อาจถูกอ้างอิงโดย Foreign Key จากตารางอื่น
หมายเหตุ: UNIQUE constraint สร้าง index อัตโนมัติ ใช้สำหรับ enforce uniqueness และเร่งการค้นหา