Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Có thể ràng buộc duy nhất tổ hợp (compound unique) trong MySQL?

Thực thi tính duy nhất tổ hợp (Composite Unique Constraint) trong MySQL

Có, MySQL hỗ trợ UNIQUE constraint trên nhiều cột (composite unique key), đảm bảo sự kết hợp của các cột là duy nhất, không phải từng cột riêng lẻ.

Cú pháp tạo bảng

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

Kiểm tra ràng buộc

Chèn bản ghi đầu tiên:

mysql> INSERT INTO enforceCompoundUniqueness(StudentName, StudentMobileNumber) 
VALUES ('Larry', '2322245676');
Query OK, 1 row affected

Chèn trùng lặp (cùng tên VÀ cùng số điện thoại):

mysql> INSERT INTO enforceCompoundUniqueness(StudentName, StudentMobileNumber) 
VALUES ('Larry', '2322245676');
ERROR 1062 (23000): Duplicate entry 'Larry-2322245676' for key 'StudentName_StudentMobileNumber'

Chèn cùng tên nhưng số khác (ĐƯỢC PHÉP):

mysql> INSERT INTO enforceCompoundUniqueness(StudentName, StudentMobileNumber) 
VALUES ('Larry', '9999999999');
Query OK, 1 row affected

Chèn cùng số nhưng tên khác (ĐƯỢC PHÉP):

mysql> INSERT INTO enforceCompoundUniqueness(StudentName, StudentMobileNumber) 
VALUES ('Sam', '2322245676');
Query OK, 1 row affected

Dữ liệu cuối cùng:

+-----------+-------------+---------------------+
| StudentId | StudentName | StudentMobileNumber |
+-----------+-------------+---------------------+
| 1         | Larry       | 2322245676          |
| 2         | Larry       | 9999999999          |
| 3         | Sam         | 2322245676          |
+-----------+-------------+---------------------+

Thêm UNIQUE cho bảng đã có

ALTER TABLE table_name ADD UNIQUE KEY uk_name_phone (name, phone);

Ứng dụng thực tế

  • User + Email (1 user có thể đổi email, nhưng không 2 user cùng email)
  • OrderId + ProductId (tránh dòng trùng trong order_detail)
  • RoomId + Date + TimeSlot (đặt phòng không trùng lịch)
  • StudentId + CourseId (đăng ký môn học không trùng)

Lưu ý

  • Tối đa 16 cột trong một index
  • Tổng độ dài index ≤ 3072 bytes (InnoDB)
  • Cho phép NULL (nhiều hàng NULL được phép trừ khi NOT NULL)