Ràng buộc Unique tổ hợp (Composite Unique) đảm bảo sự kết hợp của nhiều cột là duy nhất, không phải từng cột riêng lẻ.
Cú pháp khi tạo bảng
CREATE TABLE tên_bảng (
cột1 kiểu_dữ_liệu,
cột2 kiểu_dữ_liệu,
cột3 kiểu_dữ_liệu,
UNIQUE tên_ràng_buộc (cột2, cột3)
);
Cú pháp thêm vào bảng đã có (ALTER TABLE)
ALTER TABLE tên_bảng ADD UNIQUE tên_ràng_buộc (cột2, cột3);
Ví dụ minh họa
Tạo bảng với ràng buộc unique tổ hợp trên (StudentName, StudentAge):
mysql> CREATE TABLE UniqueDemo (
-> StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName VARCHAR(100),
-> StudentAge INT,
-> StudentMarks INT,
-> UNIQUE age_NameConstraint (StudentName, StudentAge)
-> );
Query OK, 0 rows affected (0.76 sec)
Kiểm tra index/ràng buộc:
mysql> SHOW INDEX FROM UniqueDemo;
+------------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | +------------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ | uniquedemo | 0 | PRIMARY | 1 | StudentId | A | 0 | NULL | NULL | | BTREE | | | YES | | uniquedemo | 0 | age_NameConstraint | 1 | StudentName | A | 0 | NULL | NULL | YES | BTREE | | | YES | | uniquedemo | 0 | age_NameConstraint | 2 | StudentAge | A | 0 | NULL | NULL | YES | BTREE | | | YES | +------------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
Giải thích: Seq_in_index = 1, 2 cho thấy index này bao gồm 2 cột: StudentName (thứ tự 1) và StudentAge (thứ tự 2).
Thử nghiệm ràng buộc
mysql> INSERT INTO UniqueDemo(StudentName, StudentAge, StudentMarks) VALUES ('John', 20, 85);
Query OK, 1 row affected
mysql> INSERT INTO UniqueDemo(StudentName, StudentAge, StudentMarks) VALUES ('John', 20, 90);
ERROR 1062 (23000): Duplicate entry 'John-20' for key 'age_NameConstraint'
mysql> INSERT INTO UniqueDemo(StudentName, StudentAge, StudentMarks) VALUES ('John', 21, 90);
Query OK, 1 row affected -- OK vì Age khác
Ứng dụng thực tế: Đăng ký khóa học (StudentId + CourseId), like bài viết (UserId + PostId), cấu hình hệ thống (ConfigKey + Environment), v.v.