在 SQL 中,列中的 UNIQUE
约束表示该列必须具有唯一值。
示例
-- create a table with unique constraint on college_code column
CREATE TABLE Colleges (
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
此处,college_code 列的值必须是唯一的。
SQL UNIQUE 约束语法
SQL UNIQUE
约束的语法是
CREATE TABLE table_name (
column_name data_type UNIQUE
);
这里,
table_name
是要创建的表的名称column_name
是要实现约束的列的名称data_type
是列的数据类型,例如INT
、VARCHAR
等。
创建 UNIQUE 约束
我们可以在创建表时实现 UNIQUE
约束。例如,
-- create a table with unique constraint
CREATE TABLE Colleges (
college_id INT NOT NULL UNIQUE,
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
-- insert values to Colleges table
INSERT INTO Colleges(college_id, college_code, college_name)
VALUES (1, "ARD12", "Star Public School"), (2, "ARD13", "Galaxy School");
此处,college_id
和 college_code
都具有 UNIQUE
约束。
INSERT INTO
命令成功运行,因为我们已将唯一值插入到 college_id
和 college_code
中。
另请阅读
带有 ALTER TABLE 的 UNIQUE 约束
我们还可以使用 ALTER TABLE 命令向现有列添加 UNIQUE
约束。例如,
对于单列
-- add unique constraint to an existing column
ALTER TABLE Colleges
ADD UNIQUE (college_id);
此处,SQL 命令将 UNIQUE
约束添加到现有 Colleges
表中的 colleges_id
列。
对于多列
-- add unique constraint to multiple columns
ALTER TABLE Colleges
ADD UNIQUE Unique_College (college_id, college_code);
此处,SQL 命令将 UNIQUE
约束添加到现有 Colleges
表中的 college_id
和 college_code
列。
此外,Unique_College
是为 college_id
和 college_code
列定义的 UNIQUE
约束的名称。
注意:我们的在线 SQL 编辑器不支持此操作,因为它基于 SQLite。
插入重复值时出错
如果我们尝试在具有 UNIQUE
约束的列中插入重复值,将会收到错误。
-- create a table named colleges
CREATE TABLE Colleges (
college_id INT NOT NULL UNIQUE,
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
-- insert values to Colleges table
-- college_code has duplicate values
INSERT INTO Colleges(college_id, college_code, college_name)
VALUES (1, "ARD12", "Star Public School"), (2, "ARD12", "Galaxy School");
此处,我们尝试将 ARD12 插入到 college_code 列的两个不同行中。因此,INSERT INTO 命令导致错误。
为唯一值创建 UNIQUE INDEX
如果我们要为列中的唯一值创建索引,我们使用 CREATE UNIQUE INDEX
约束。例如,
-- create unique index
CREATE UNIQUE INDEX college_index
ON Colleges(college_code);
此处,SQL 命令使用 college_code 列在 Colleges 表上创建一个名为 college_index 的唯一索引。
注意:创建索引不会更改表中的原始数据。
另请阅读