MySQL Trigger: Deleting Data from a Related Table Upon Deletion
When managing database tables, it is common to encounter scenarios where changes in one table should cascade to other related tables. In this specific instance, the task at hand is to create a MySQL trigger that ensures that upon deleting a record from the "patrons" table, the corresponding information associated with that patron in the "patron_info" table is also removed.
Trigger Implementation
To achieve this, the following trigger can be defined:
<code class="sql">CREATE TRIGGER log_patron_delete AFTER DELETE on patrons FOR EACH ROW BEGIN DELETE FROM patron_info WHERE patron_info.pid = old.id; END</code>
Here's a breakdown of the trigger:
It is important to note that the correct position of the semicolon at the end of the DELETE statement is crucial for the trigger to execute properly. Additionally, when executing the trigger code in a console window, delimiters should be used to prevent syntax errors.
The above is the detailed content of How to Delete Related Data in a MySQL Trigger: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!