Why do we need to use Foreign Keys? [duplicate]

非 Y 不嫁゛ 提交于 2019-12-03 13:39:27

When you use foreign keys you get:

  1. Data integrity
  2. faster queries.

users:
user id:

  • 1
  • 2
  • 3

Comments:
user:

  • 1
  • 2
  • 4 XXX invalid as 4 isn't in the users table.

Read Wikipedia please for more details about Data integrity

It creates data integrity in the database. Consider you remove an users, then you would end up with a lot of comments linked to an invalid user if you forget to remove the comments manually with a separate query. With foreign keys you could set it to remove all the comments automatically as you remove an user (or update changes, like if you would change the user id).

Firstly - foreing key is a constraint. If you have 1-to-many or many-to-many relations in database, foreign keys will be very useful. Find more information here - Referential integrity.

Also they have some good actions - RESTRICT, CASCADE, SET NULL, NO ACTION; read this information in documentation.

So, foreign keys and database itself can do some work for you.

By making it a foreign key you are enforcing the relationship between the tables If you have a foreign key you can't put a user_id that is not in the user table.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!