如果可以使用 WHERE,为什么还需要使用外键?
一个关于 MySQL 中外键的初学者问题.
A beginners' question about foreign key in MySQL.
在 w3school 中说,
一个表中的 FOREIGN KEY 指向另一个表中的 PRIMARY KEY.
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
还有WHERE,
WHERE id = page_id
那么如果我可以使用 WHERE 来链接表,那么拥有外键的主要目的是什么?
So if I can use WHERE for linking the tables, what is the main purpose of having foreign key?
推荐答案
查询不是严格需要的,这是真的.它的存在有几个原因:
It's not strictly needed for the query, it's true. It exists for several reasons:
- 作为对表的约束,以阻止您插入不指向任何内容的内容;
- 作为优化器的线索;和
- 由于历史原因,哪里更需要.
(1) 可能是三者中最重要的一个.这称为 参照完整性.这意味着如果外键中有一个值,那么在父表中就会有一条以该值作为主键的对应记录.
(1) is probably the important one of the three. This is called referential integrity. It means that if there is a value in a foreign key there will be a corresponding record with that value as a primary key in the parent table.
话虽如此,并非所有数据库都支持参照完整性(例如 MySQL/MyISAM 表),并且那些不一定强制执行的数据库(出于性能原因).
That being said, not all databases support referential integrity (eg MySQL/MyISAM tables) and those that do don't necessarily enforce it (for performance reasons).
相关文章