Why use Foreign Key constraints in MySQL?(为什么在 MySQL 中使用外键约束?)
问题描述
我在想,
我在 MySQL 中使用约束作为外键的动机是什么,因为我确信我可以控制添加的类型?
What will be my motivation to use constraint as foreign key in MySQL, as I am sure that I can rule the types that are added?
它会提高性能吗?
推荐答案
外键 强制参照完整性.这些约束保证表 order_details 中带有字段 order_id 引用 orders 表的行永远不会有 order_id orders 表中不存在的值.
Foreign keys enforce referential integrity. These constraints guarantee that a row in a table order_details with a field order_id referencing an orders table will never have an order_id value that doesn't exist in the orders table.
外键不需要有一个工作的关系数据库(事实上 MySQL 的默认存储引擎不支持 FK),但它们对于避免破坏关系和孤立行(即参照完整性)绝对是必不可少的.ACID<中的 C 需要在数据库级别强制执行参照完整性的能力/a> 站立.
Foreign keys aren't required to have a working relational database (in fact MySQL's default storage engine doesn't support FKs), but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity). The ability to enforce referential integrity at the database level is required for the C in ACID to stand.
至于您对性能的担忧,通常会有性能成本,但可能可以忽略不计.我建议放入所有外键约束,并且仅在遇到无法通过其他方式解决的实际性能问题时才尝试不使用它们.
As for your concerns regarding performance, in general there's a performance cost, but will probably be negligible. I suggest putting in all your foreign key constraints, and only experiment without them if you have real performance issues that you cannot solve otherwise.
这篇关于为什么在 MySQL 中使用外键约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 MySQL 中使用外键约束?
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
