唯一键
一句话解释
唯一键 是 constraint 那个 prevents duplicate 值 in 列 — 每个值 必须是 不同.
用大白话说
A unique key ensures that no two rows in a table have the same value in the constrained column (or combination of columns). This is useful for things like email addresses, usernames, or product codes — values that should never be duplicated.
A primary key is always unique, but a table can have multiple unique keys in addition to the primary key. For example, a 用户 table might have id as the primary key and email as a unique key — both are unique, but id is the primary identifier.
Unlike a primary key, a unique key can technically allow NULL values (depending on the DBMS), and you can have many unique keys per table.
示例
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
username TEXT UNIQUE NOT NULL
);
-- Both email and username must be uniqueUNIQUE constraint prevents two 用户从 registering 使用相同 email or 用户名.
常见混淆
容易混淆的对象: 主键
关键区别: 主键是 主要 identifier and cannot 是 NULL; 唯一键 只是 prevents duplicates and 你能 有几个每 表.
相关术语
相关资源
相关课程
- Constraints
学习关于唯一键 and other constraints.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。