SQL 外键与连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2947440/
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
Foreign Keys vs Joins
提问by andrew Sullivan
Is it better to use foreign keys in tables or can the same results be achieved with joins?
在表中使用外键更好还是可以通过连接获得相同的结果?
回答by Daniel Vassallo
Foreign keysare just constraints to enforce referential integrity. You will still need to use JOINsto build your queries.
外键只是强制执行参照完整性的约束。您仍然需要使用JOIN来构建查询。
Foreign keys 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. 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).
外键保证表中order_details
具有order_id
引用表的字段的行orders
永远不会有表order_id
中不存在的值orders
。外键不需要有一个工作关系数据库(事实上MySQL 的默认存储引擎不支持 FKs),但它们对于避免破坏关系和孤立行(即参照完整性)绝对是必不可少的。
回答by lexu
FOREIGN KEY
sand JOIN
sdon't do the same thing!
FOREIGN KEY
s和JOIN
s不做同样的事情!
- A
FOREIGN KEY
enforces data integrity, making sure the data confirms to some rules when it is added to the DB. A
JOIN
is used when you extract/query data from the DB by giving rules how to select the data.JOIN
s work if there are FK or not.- FK's work if you extract data with or without
JOIN
s.
- A
FOREIGN KEY
强制执行数据完整性,确保数据在添加到数据库时符合某些规则。 JOIN
当您通过给出如何选择数据的规则从数据库中提取/查询数据时使用A。JOIN
无论是否有 FK 都可以工作。- 如果您使用或不使用
JOIN
s提取数据,FK 的工作。
CONCLUSION:FK and JOIN
don't allow you to achieve the same goal!
结论:FK和JOIN
不要让你达到同样的目标!