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

บังคับความ unique แบบรวมหลายคอลัมน์ (Compound Unique) ใน MySQL


แนวคิด

Compound Unique Constraint บังคับให้ชุดคอลัมน์ (หลายคอลัมน์รวมกัน) ไม่มีค่าซ้ำ แต่ว่างๆ อาจซ้ำได้

รูปแบบคำสั่งตอนสร้างตาราง

CREATE TABLE yourTableName (
    yourColumnName1 datatype,
    yourColumnName2 datatype,
    yourColumnName3 datatype,
    ...
    UNIQUE yourConstraintName (yourColumnName2, yourColumnName3)
);

ตัวอย่างเต็มรูปแบบ

1. สร้างตารางพร้อม Compound Unique

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)

Constraint นี้บังคับว่า ไม่มี 2 คนที่ชื่อและอายุเหมือนกันทั้งคู่ (แต่ชื่อซ้ำได้ถ้าอายุต่างกัน และอายุซ้ำได้ถ้าชื่อต่างกัน)

2. ตรวจสอบ Index/Constraint

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     |
+------------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+

เห็นว่า age_NameConstraint มี Seq_in_index 1 และ 2 แสดงว่าเป็น composite index 2 คอลัมน์

3. เพิ่ม Constraint ให้ตารางที่มีอยู่แล้ว

ALTER TABLE existing_table ADD UNIQUE constraint_name (col1, col2);

กรณีใช้งานจริง

  • Enrollment: (student_id, course_id) - นักเรียน 1 คน ลงทะเบียนวิชาเดียวกันได้ 1 ครั้ง
  • Schedule: (room_id, start_time) - ห้องเดียวจองเวลาซ้ำไม่ได้
  • Social: (user_id, friend_id) - เพื่อนร่วมกัน 1 คู่

ข้อควรระวัง: คอลัมน์ใน UNIQUE constraint ควรเป็น NOT NULL เพื่อป้องกันปัญหา NULL comparison (NULL != NULL ใน SQL)