外键
一句话解释
外键是 列 in one 表那个引用主键的 another 表, 创建链接之间 two.
用大白话说
A foreign key is how you connect rows in one table to rows in another. The foreign key column holds a value that must match the primary key of a row in the referenced table.
例如, if an 顺序 table has a user_id column that references 用户(id), then each order is linked to the user who placed it. The database enforces this — you cannot insert an order with a user_id that does not exist in the 用户 table.
Foreign keys enforce referential integrity: you cannot delete a user who still has orders (unless you set up cascading deletes), and you cannot create an orphan order pointing to a non-existent user.
示例
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total NUMERIC(10,2)
);
-- user_id is a foreign key pointing to users.id user_id 外键 ensures 每个顺序是 链接到 真实用户 — 否 orphan 顺序.
常见混淆
容易混淆的对象: 主键
关键区别: 主键唯一地 identifies 行 in 这个表; 外键点 到主键的 another 表. 列能 是两者都, 但它们 serve 不同 purposes.
相关术语
相关资源
相关课程
- 关系
学习如何 foreign 键创建表 关系.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。