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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:25:03  来源:igfitidea点击:

Foreign Keys vs Joins

sql

提问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_detailswith a field order_idreferencing an orderstable will never have an order_idvalue that doesn't exist in the orderstable. 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 KEYsand JOINsdon't do the same thing!

FOREIGN KEYsJOINs不做同样的事情!

  • A FOREIGN KEYenforces data integrity, making sure the data confirms to some rules when it is added to the DB.
  • A JOINis used when you extract/query data from the DB by giving rules how to select the data.

  • JOINs work if there are FK or not.

  • FK's work if you extract data with or without JOINs.
  • AFOREIGN KEY强制执行数据完整性,确保数据在添加到数据库时符合某些规则。
  • JOIN当您通过给出如何选择数据的规则从数据库中提取/查询数据时使用A。

  • JOIN无论是否有 FK 都可以工作。

  • 如果您使用或不使用JOINs提取数据,FK 的工作。

CONCLUSION:FK and JOINdon't allow you to achieve the same goal!

结论:FK和JOIN不要让你达到同样的目标!