为什么在 MySQL 中使用外键约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3433975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why use Foreign Key constraints in MySQL?
提问by Dejell
I was wondering,
我想知道,
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?
我在 MySQL 中使用约束作为外键的动机是什么,因为我确信我可以规则添加的类型?
Does it improve performance?
它会提高性能吗?
回答by Daniel Vassallo
Foreign keysenforce 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.
外键强制参照完整性。这些约束保证表中order_details
具有order_id
引用表的字段的行orders
永远不会有表order_id
中不存在的值orders
。
Foreign keys aren't required to have a working relational database (in fact MySQL's default storageengine 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 Cin ACIDto stand.
外键不需要有一个工作关系数据库(事实上MySQL 的默认存储引擎不支持 FKs),但它们对于避免破坏关系和孤立行(即参照完整性)绝对是必不可少的。是必需的在数据库级别实施参照完整性的能力Ç在ACID站。
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.
至于您对性能的担忧,通常会有性能成本,但可能可以忽略不计。我建议放入所有外键约束,并且只有在遇到无法通过其他方式解决的实际性能问题时才进行试验。