Why do I need to use foreign key if I can use WHERE?(如果可以使用 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).
这篇关于如果可以使用 WHERE,为什么还需要使用外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果可以使用 WHERE,为什么还需要使用外键?
基础教程推荐
- 是否可以执行按位分组功能? 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
