When designing a table, how to choose a foreign key depends on these rules, the most complete in the whole network

When designing database tables, whether you need foreign keys depends on your business needs and data consistency requirements. Here are some ideas for judging whether foreign keys are needed:

1. Data association: If there is a direct data association between two tables, then a foreign key needs to be set. For example, there is an obvious data correlation between the order table and the user table, product table, and merchant table. The order obviously needs to know which user placed the order, which product was purchased, and which merchant it came from, so it is necessary to set the user ID, product ID and Merchant ID as foreign keys.

2. Data consistency: If you need to ensure data consistency, you also need to set a foreign key. For example, if a user is deleted, the orders related to this user should also be deleted, which requires setting a foreign key and cascading deletion.

3. Query efficiency: Sometimes, in order to improve query efficiency, foreign keys are also set. If you often need to join two tables for query, setting foreign keys can improve query efficiency.

4. Business logic: Sometimes, although there is no direct data correlation between the two tables, foreign keys need to be set because of the needs of business logic. For example, there may be a table used to record user behavior. Although this table has no direct data correlation with the user table, the user ID may also be set as a foreign key to facilitate subsequent analysis of user behavior.

It is not a necessary foreign key, maybe because the relationship between the two tables is not strong, or there is no need to ensure data consistency, or there is no need to improve query efficiency, or there is no need for business logic. When designing a table, you can judge whether you need to set a foreign key based on the above ideas.

Guess you like

Origin blog.csdn.net/weixin_42759398/article/details/131443276