What exactly are MySQL triggers? MySQL creates a trigger (CREATE TRIGGER)

MySQL triggers, like stored procedures, are programs embedded in MySQL and are powerful tools for data management in MySQL. The difference is that the execution of the stored procedure requires the use of the CALL statement, while the execution of the trigger does not require the use of the CALL statement, nor does it need to be started manually. Instead, it is triggered and activated through related operations on the data table to achieve execution. For example, it will be activated when an operation (INSERT, DELETE or UPDATE) is performed on the student table.

Triggers are closely related to data tables and are mainly used to protect the data in the tables. Especially when there are multiple tables that are related to each other, triggers can maintain data consistency in different tables.

In MySQL, triggers can only be activated when performing INSERT, UPDATE, and DELETE operations, and other SQL statements will not activate triggers.

So why use triggers? For example, when actually developing projects, we often encounter the following situations:

  • When a record about a student is added to the student table, the total number of students must also change.
  • When adding a student record, you need to check whether the age meets the range requirements.
  • When deleting a student's information, the corresponding record on the grade sheet needs to be deleted.
  • When a piece of data is deleted, a backup copy needs to be retained in the database archive table.

 
Although the business logic implemented in the above situations is different, they all need to automatically perform some processing when the data table changes. At this time, trigger processing can be used. For example, for the first case, you can create a trigger object and perform an operation to calculate the total number of students every time a student record is added. This ensures that every time a student record is added, the total number of students and the number of student records are calculated. are consistent.

Advantages and Disadvantages of Triggers

The advantages of triggers are as follows:

  • The execution of the trigger is automatic and is executed immediately after the corresponding modifications are made to the data in the trigger-related table.
  • Triggers can implement more complex checks and operations than FOREIGN KEY constraints and CHECK constraints.
  • Triggers can implement cascading changes to table data, ensuring data integrity to a certain extent.


The disadvantages of triggers are as follows:

  • Business logic implemented using triggers is difficult to locate when problems occur, especially when multiple triggers are involved, making later maintenance difficult.
  • Extensive use of triggers can easily disrupt the code structure and increase the complexity of the program.
  • If the amount of data that needs to be changed is large, the execution efficiency of the trigger will be very low.

Triggers supported by MySQL

In actual use, MySQL supports three triggers: INSERT trigger, UPDATE trigger and DELETE trigger.

1) INSERT trigger

A trigger that responds before or after an INSERT statement is executed.

When using INSERT triggers, you need to pay attention to the following points:

  • Within the INSERT trigger code, a virtual table named NEW (case-insensitive) can be referenced to access the inserted row.
  • In the BEFORE INSERT trigger, the value in NEW can also be updated, which allows the inserted value to be changed (as long as it has the corresponding operation permissions).
  • For the AUTO_INCREMENT column, NEW contains the value 0 before the INSERT is executed and will contain the new automatically generated value after the INSERT is executed.
2) UPDATE trigger

A trigger that responds before or after an UPDATE statement is executed.

When using UPDATE triggers, you need to pay attention to the following points:

  • Within the UPDATE trigger code, a virtual table named NEW (case-insensitive) can be referenced to access the updated value.
  • Within the UPDATE trigger code, a virtual table named OLD (case-insensitive) can be referenced to access the value before the UPDATE statement was executed.
  • In a BEFORE UPDATE trigger, the value in NEW may also be updated, which allows changes to the value to be used in the UPDATE statement (as long as you have the corresponding operation permissions).
  • All values ​​in OLD are read-only and cannot be updated.


Note: When the trigger is designed to trigger the update operation of the table itself, only BEFORE type triggers can be used, and AFTER type triggers will not be allowed.

3) DELETE trigger

A trigger that responds before or after a DELETE statement is executed.

When using the DELETE trigger, you need to pay attention to the following points:

  • Within the DELETE trigger code, a virtual table named OLD (case-insensitive) can be referenced to access the deleted rows.
  • All values ​​in OLD are read-only and cannot be updated.


Generally speaking, MySQL will handle errors in the following way during trigger use.

For transactional tables, if the trigger fails and the entire statement fails as a result, all changes performed by the statement will be rolled back; for non-transactional tables, such rollback cannot be performed even if the statement fails. Any previous changes will still be in effect.

If the BEFORE trigger fails, MySQL will not perform the operation on the corresponding row.

If an error occurs during the execution of a BEFORE or AFTER trigger, the entire statement that calls the trigger will fail.

MySQL will execute the AFTER trigger only if both the BEFORE trigger and the row operation have been successfully executed.

MySQL creates a trigger (CREATE TRIGGER)

Triggers are database objects related to  MySQL  data tables. They are triggered when defined conditions are met and execute the set of statements defined in the trigger. This feature of triggers can help applications ensure data integrity on the database side.

Mysql database basic skills full practice icon-default.png?t=N7T8https://edu.csdn.net/course/detail/36210

basic grammar

In MySQL 5.7, triggers can be created using the CREATE TRIGGER statement.

The syntax format is as follows:

CREATE <触发器名> < BEFORE | AFTER >
<INSERT | UPDATE | DELETE >
ON <表名> FOR EACH Row<触发器主体>

The syntax is explained below.

1) Trigger name

The name of the trigger. The trigger must have a unique name in the current database. If you are creating in a specific database, the name should be preceded by the name of the database.

2) INSERT | UPDATE | DELETE

Trigger event, used to specify the type of statement that activates the trigger.

Note: The execution times of the three triggers are as follows.

  • INSERT: Trigger activated when a new row is inserted into the table. For example, the BEFORE trigger of INSERT can be activated not only by the INSERT statement of MySQL, but also by the LOAD DATA statement.
  • DELETE: Triggers are activated when a row of data is deleted from the table, such as DELETE and REPLACE statements.
  • UPDATE: A trigger is activated when a row of data in the table is changed, such as an UPDATE statement.
3) BEFORE | AFTER

BEFORE and AFTER, the moment when the trigger is fired, indicate whether the trigger is fired before or after the statement that activates it. If you want to verify whether the new data meets the conditions, use the BEFORE option; if you want to complete several or more changes after the statement that activates the trigger is executed, you usually use the AFTER option.

4) Table name

The name of the table that the trigger is associated with. This table must be a permanent table. The trigger cannot be associated with a temporary table or view. The trigger is activated when a trigger event occurs on the table. The same table cannot have two triggers with the same firing time and event. For example, for a data table, there cannot be two BEFORE UPDATE triggers at the same time, but there can be a BEFORE UPDATE trigger and a BEFORE INSERT trigger, or a BEFORE UPDATE trigger and an AFTER UPDATE trigger.

5) Trigger body

The trigger action body contains the MySQL statement that will be executed when the trigger is activated. If you want to execute multiple statements, you can use the BEGIN…END compound statement structure.

6) FOR EACH ROW

Generally refers to row-level triggering, where the trigger action must be activated for each row affected by the triggering event. For example, when using the INSERT statement to insert multiple rows of data into a table, the trigger will perform corresponding trigger actions for each row of data inserted.

注意:每个表都支持 INSERT、UPDATE 和 DELETE 的 BEFORE 与 AFTER,因此每个表最多支持 6 个触发器。每个表的每个事件每次只允许有一个触发器。单一触发器不能与多个事件或多个表关联。

In addition, in MySQL, if you need to view the existing triggers in the database, you can use the SHOW TRIGGERS statement.

Create a BEFORE type trigger

In the test_db database, the data table tb_emp8 is an employee information table, including id, name, deptId and salary fields. The table structure of the data table tb_emp8 is as follows.

mysql> SELECT * FROM tb_emp8;
Empty set (0.07 sec)
mysql> DESC tb_emp8;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id     | int(11)     | NO   | PRI | NULL    |       |
| name   | varchar(22) | YES  | UNI | NULL    |       |
| deptId | int(11)     | NO   | MUL | NULL    |       |
| salary | float       | YES  |     | 0       |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.05 sec)

[Example 1] Create a trigger named SumOfSalary. The trigger condition is to sum up the newly inserted salary field values ​​before inserting data into the data table tb_emp8. The input SQL statement and execution process are as follows.

mysql> CREATE TRIGGER SumOfSalary
    -> BEFORE INSERT ON tb_emp8
    -> FOR EACH ROW
    -> SET @sum=@sum+NEW.salary;
Query OK, 0 rows affected (0.35 sec)

After the trigger SumOfSalary is created, when a record is inserted into the table tb_emp8, the defined sum value changes from 0 to 1500, that is, the sum of the inserted values ​​​​1000 and 500, as shown below.

SET @sum=0;
Query OK, 0 rows affected (0.05 sec)
mysql> INSERT INTO tb_emp8
    -> VALUES(1,'A',1,1000),(2,'B',1,500);
Query OK, 2 rows affected (0.09 sec)
Records: 2  Duplicates: 0  Warnings: 0
mysql> SELECT @sum;
+------+
| @sum |
+------+
| 1500 |
+------+
1 row in set (0.03 sec)

Create AFTER type trigger

In the test_db database, the data tables tb_emp6 and tb_emp7 are both employee information tables, including id, name, deptId and salary fields. The table structures of the data tables tb_emp6 and tb_emp7 are as follows.

mysql> SELECT * FROM tb_emp6;
Empty set (0.07 sec)
mysql> SELECT * FROM tb_emp7;
Empty set (0.03 sec)
mysql> DESC tb_emp6;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id     | int(11)     | NO   | PRI | NULL    |       |
| name   | varchar(25) | YES  |     | NULL    |       |
| deptId | int(11)     | YES  | MUL | NULL    |       |
| salary | float       | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
mysql> DESC tb_emp7;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id     | int(11)     | NO   | PRI | NULL    |       |
| name   | varchar(25) | YES  |     | NULL    |       |
| deptId | int(11)     | YES  |     | NULL    |       |
| salary | float       | YES  |     | 0       |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.04 sec)

[Example 2] Create a trigger named double_salary. The trigger condition is that after inserting data into the data table tb_emp6, the same data is inserted into the data table tb_emp7, and the salary is 2 of the newly inserted salary field value in tb_emp6. times. The input SQL statement and execution process are as follows.

mysql> CREATE TRIGGER double_salary
    -> AFTER INSERT ON tb_emp6
    -> FOR EACH ROW
    -> INSERT INTO tb_emp7
    -> VALUES (NEW.id,NEW.name,deptId,2*NEW.salary);
Query OK, 0 rows affected (0.25 sec)

After the trigger double_salary is created, when a record is inserted into table tb_emp6, the same record is inserted into table tb_emp7 at the same time, and the salary field is twice the value of the salary field in tb_emp6, as shown below.

mysql> INSERT INTO tb_emp6
    -> VALUES (1,'A',1,1000),(2,'B',1,500);
Query OK, 2 rows affected (0.09 sec)
Records: 2  Duplicates: 0  Warnings: 0
mysql> SELECT * FROM tb_emp6;
+----+------+--------+--------+
| id | name | deptId | salary |
+----+------+--------+--------+
|  1 | A    |      1 |   1000 |
|  2 | B    |      1 |    500 |
+----+------+--------+--------+
3 rows in set (0.04 sec)
mysql> SELECT * FROM tb_emp7;
+----+------+--------+--------+
| id | name | deptId | salary |
+----+------+--------+--------+
|  1 | A    |      1 |   2000 |
|  2 | B    |      1 |   1000 |
+----+------+--------+--------+
2 rows in set (0.06 sec)

Dachang senior database engineer mysql database practical training icon-default.png?t=N7T8https://edu.csdn.net/course/detail/39021

Guess you like

Origin blog.csdn.net/m0_37449634/article/details/135553488