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

บังคับ Compound Uniqueness ใน MySQL

Unique Constraint แบบหลายคอลัมน์ (Composite Unique)

ใช้ UNIQUE KEY รวมหลายคอลัมน์ เพื่อบังคับให้ชุดค่าร่วมกันไม่ซ้ำ

สร้างตาราง

CREATE TABLE enforceCompoundUniqueness (
    StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    StudentName VARCHAR(40) NOT NULL,
    StudentMobileNumber VARCHAR(12) NOT NULL,
    UNIQUE KEY StudentName_StudentMobileNumber (StudentName, StudentMobileNumber)
);

ทดสอบ Insert

INSERT INTO enforceCompoundUniqueness(StudentName, StudentMobileNumber) VALUES ('Larry', '2322245676'); -- OK
INSERT INTO enforceCompoundUniqueness(StudentName, StudentMobileNumber) VALUES ('Larry', '2322245676'); -- ERROR 1062
INSERT INTO enforceCompoundUniqueness(StudentName, StudentMobileNumber) VALUES ('Sam', '6475746455'); -- OK

ผลลัพธ์

+-----------+-------------+---------------------+
| StudentId | StudentName | StudentMobileNumber |
+-----------+-------------+---------------------+
| 1         | Larry       | 2322245676          |
| 3         | Sam         | 6475746455          |
+-----------+-------------+---------------------+

การทำงาน

  • (Larry, 2322245676) ซ้ำ → Error
  • (Larry, หมายเลขอื่น) → OK
  • (คนอื่น, 2322245676) → OK
  • เฉพาะชุด (Name + Mobile) เดียวกันเท่านั้นที่ห้าม

เพิ่ม Unique Key ภายหลัง

ALTER TABLE table_name ADD UNIQUE KEY key_name (col1, col2);