Tạo khóa duy nhất tổ hợp (Composite Unique Key) trong MySQL
Sử dụng ALTER TABLE ... ADD UNIQUE để thêm ràng buộc unique trên nhiều cột cho bảng đã tồn tại.
Cú pháp
ALTER TABLE yourTableName ADD UNIQUE yourUniqueName (col1, col2, ...);
Ví dụ: Thêm unique cho (StudentName, StudentAge, StudentGrade)
Tạo bảng:
mysql> CREATE TABLE makeCompositeKeyDemo (
-> Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName VARCHAR(40),
-> StudentAge INT,
-> StudentGrade CHAR(1)
-> );
Cấu trúc ban đầu:
+--------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(40) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentGrade | char(1) | YES | | NULL | | +--------------+-------------+------+-----+---------+----------------+
Thêm UNIQUE composite key:
mysql> ALTER TABLE makeCompositeKeyDemo ADD UNIQUE Name_Age_Grade (StudentName, StudentAge, StudentGrade); Query OK, 0 rows affected (0.69 sec)
Cấu trúc sau khi thêm (Key = MUL cho các cột trong unique key):
+--------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(40) | YES | MUL | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentGrade | char(1) | YES | | NULL | | +--------------+-------------+------+-----+---------+----------------+
Kiểm tra ràng buộc
INSERT INTO makeCompositeKeyDemo(StudentName, StudentAge, StudentGrade) VALUES ('A', 20, 'A'); -- OK
INSERT INTO makeCompositeKeyDemo(StudentName, StudentAge, StudentGrade) VALUES ('A', 20, 'A'); -- ERROR 1062
INSERT INTO makeCompositeKeyDemo(StudentName, StudentAge, StudentGrade) VALUES ('A', 20, 'B'); -- OK (Grade khác)
INSERT INTO makeCompositeKeyDemo(StudentName, StudentAge, StudentGrade) VALUES ('A', 21, 'A'); -- OK (Age khác)
Lưu ý
- Tên unique key (
Name_Age_Grade) phải duy nhất trong bảng - Thứ tự cột trong unique key ảnh hưởng đến khả năng dùng index cho query prefix
- Cho phép NULL (nhiều hàng NULL OK trừ khi cột NOT NULL)
- Xóa:
ALTER TABLE ... DROP INDEX Name_Age_Grade