Skip to content

主键

一句话解释

主键是 列谁的值 唯一地 identifies 每个行 — 否 two 行 share 相同主键值, and 它 cannot 是 NULL.

用大白话说

A primary key is the unique identifier for each row in a table. No two rows can have the same primary key value, and the value cannot be NULL. This guarantees that you can always find exactly one row by its primary key.

Common choices for primary keys are an auto-incrementing integer (SERIAL in PostgreSQL, AUTO_INCREMENT in MySQL) or a UUID. The auto-incrementing integer is simple and fast; UUIDs are useful when you generate IDs across multiple systems.

A table can have only one primary key, though it can be composed of multiple columns (a composite key). Every table should have a primary key — it is the foundation of relationships and indexing.

示例

sql
CREATE TABLE users (
  id    SERIAL PRIMARY KEY,
  name  TEXT NOT NULL
);
-- 'id' is the primary key: unique, not null, auto-incrementing

id 列是 主键 — PostgreSQL auto-assigns 1, 2, 3, ... for 每个新 行.

常见混淆

  • 容易混淆的对象: 唯一键

    关键区别: 主键 cannot 是 NULL and 那里是 仅 one 每表; 唯一键 能允许 NULL (depending on DBMS) and 你能 有许多每 表.

  • 容易混淆的对象: 外键

    关键区别: 主键 identifies 行 in 这个表; 外键引用主键的 another 表到 创建关系.

相关术语

相关资源

相关课程

  • Constraints

    学习关于主要键 and other constraints.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表