Answer the question
In order to leave comments, you need to log in
Creating records in related tables - through MySQL triggers or in application code?
We have a MySQL database (InnoDB) or similar.
Suppose the data is split into two tables: user and user_profile. Accordingly, the data in user_profile is related 1 to 1 with the data in user.
Programmers, in such cases, most often in the code in a transaction wrap the creation of an entry in user, followed by the creation of an associated entry in user_profile.
DBA-shchiki ( for example ) insist that it is more correct to take it out in the database (database first), hang up a trigger that, when creating a record in user, will create an associated record in user_profile.
The method through the code has such pluses and minuses:
+ Visibility. Any programmer immediately understands that this is where a record and other records are created in related tables.
+ Support for any database
- Everyone should always remember to create records in related tables (there may be several, they may change).
- New people may not be able to "transaction", be unaware of all connections, etc.
- Using the database as a "stupid" storage with a lot of possibilities.
The method through the database has the following pros and cons:
+ 100% consistency
+ Simplification of the application code - code code, base - basic.
- For new programmers, this behavior can be "magic".
- Not supported by all databases (probably)
- There is a chance to forget to add a trigger when adding a new related table
- When moving to another database, you need to remember about triggers.
Answer the question
In order to leave comments, you need to log in
Suppose that there is a lot of data and we need to spread these tables about different databases on different servers.
Then DBAs will suck pisos with storages and FK (we consider this in the MySQL topic)
Then only transactions or maintaining data consistency at the application level
Triggers are not a very obvious thing, so if you want to drag part of the logic into the database, then it is better to make a procedure for this.
The third option: stored procedure[s]* - at the input, which receives the necessary data for adding/changing, which, within the framework of the transaction, perform checks-records-calculations ... moreover, then the "magic" of the contacts tied to the profile (there are more than 1 plates: 1) can be hidden in the same place... as well as notifications about changing sensitive data, logging, and something else potentially needed... moreover, the latter - in fact, it will not require anything to be changed outside of such a procedure.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question