开发者

Foreign Keys vs Joins

Is it better to use foreign keys in table开发者_开发问答s or can the same results be achieved with joins?


Foreign keys are just constraints to enforce referential integrity. You will still need to use JOINs to build your queries.

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 storage engine doesn't support FKs), but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity).


FOREIGN KEYs and JOINs don't do the same thing!

  • A FOREIGN KEY enforces data integrity, making sure the data conforms 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.

  • JOINs work if there are FK or not.

  • FK's work if you extract data with or without JOINs.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜