UNIQUE 唯一約束
UNIQUE 約束確保欄位中的值不會重複,每個值在該欄位中都是唯一的。
與 PRIMARY KEY 不同的是:
- 一個資料表可以有多個 UNIQUE 欄位
- UNIQUE 欄位可以接受 NULL 值
建立資料表時設定
CREATE TABLE users (
id INT NOT NULL,
username VARCHAR(50) UNIQUE,
email VARCHAR(100) UNIQUE
);
也可以寫在資料表定義的最後:
CREATE TABLE users (
id INT NOT NULL,
username VARCHAR(50),
email VARCHAR(100),
UNIQUE (username),
UNIQUE (email)
);
命名約束條件
為約束條件命名,方便日後管理:
CREATE TABLE users (
id INT NOT NULL,
email VARCHAR(100),
CONSTRAINT uq_user_email UNIQUE (email)
);
多欄位組合唯一
限制多個欄位的組合必須唯一:
CREATE TABLE enrollments (
student_id INT,
course_id INT,
CONSTRAINT uq_enrollment UNIQUE (student_id, course_id)
);
這表示同一個學生不能重複選修同一門課。
新增 UNIQUE 約束
ALTER TABLE users ADD UNIQUE (email);
-- 或命名約束
ALTER TABLE users ADD CONSTRAINT uq_user_email UNIQUE (email);
移除 UNIQUE 約束
-- MySQL
ALTER TABLE users DROP INDEX uq_user_email;
-- SQL Server / PostgreSQL
ALTER TABLE users DROP CONSTRAINT uq_user_email;