Database design -- foreign key design

Database design -- foreign key design

 

 

  • The purpose of foreign keys: to ensure the integrity of data through the database and improve the efficiency of associated queries
  • Side effects of foreign keys: Inserts or updates are less efficient.

 

 

 

Why do foreign keys have performance issues?

 

  • The database needs to maintain the internal management of foreign keys;
  • The foreign key is equal to the realization of the consistent transaction of the data, all of which are handed over to the database server to complete;
  • With foreign keys, after adding, deleting, and updating operations involving foreign key fields, you need to trigger related operations to check, and you have to consume resources;
  • Foreign keys are also prone to deadlocks because they need to request internal locks on other tables;

 

 

 

 

foreign key naming

 

  • fk_business: For example, to register business, the user table has a foreign key, which can be named, fk_user_register
  • fk_current table name_main table name: For example, login, user_session table has a user_id foreign key, which can be named, fk_user_session_user

 

 

 

 

Should I use foreign keys?

 

to use

 

    Data completeness is guaranteed through the database. When there are many associated queries between two tables, and the amount of data is not large, the efficiency of insert or update can be ignored.

 

    E.g:

 

  • The number of software applications is limited, in other words controllable;
  • The data volume of the database server is generally not too large, and the active data is limited;

 

 

available, optional

 

    Data incompleteness can be tolerated. Or think that the program can already control the integrity of the data.

 

    When there are many associated queries between two tables, but the amount of data in the two tables is not large or there are many associated queries between the two tables, the query efficiency is not high, and the efficiency of insertion or update is high.

 

 

 

Need not

 

    There is no logical relationship between the two tables, and the efficiency of insertion or update is very high; or there is a logical relationship, but the logical relationship can be controlled through the intermediate business layer, which has better scalability.

 

    E.g:

 

    Internet applications: The number of users is large and the degree of concurrency is high. For this reason, the database server can easily become a performance bottleneck, especially limited by the IO capability, and cannot be easily scaled horizontally; if the control of data consistency is placed in the transaction, that is, the application The server bears the pressure of this part, and the reference server can generally be easily scaled horizontally;

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326100517&siteId=291194637