问题描述
我在想,
我在 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 中使用外键约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!