12_MySQL trigger

1. Introduction to MySQL Trigger

The MySQL trigger is a special stored procedure, the difference is that the execution of the stored procedure requires the use of call to call, and the execution of the trigger does not need to use the call to call, nor does it need to be manually started, as long as a predefined event occurs, it will be called by MySQL. Called automatically.

The events that trigger the execution of the trigger are generally as follows:

  • When adding a student record, it will automatically check whether the age meets the scope requirements.
  • Whenever a piece of student information is deleted, the corresponding record on the score sheet will be deleted automatically.
  • Whenever a piece of data is deleted, a backup copy is kept in the database archive table.

Advantages of the trigger:

  • The execution of the trigger program is automatic, and it will be executed immediately after corresponding changes are made to the data in the trigger program related table.
  • The trigger can modify other tables through the cascade of related tables in the database.
  • The trigger can implement more complex checks and operations than foreign key (foreign key) constraints and check constraints.

The trigger is closely related to the table and is mainly used to protect the data in the table. Especially when there are multiple tables with a certain degree of mutual connection, triggers can allow different tables to maintain data consistency.

Triggers can only be activated when INSERT, UPDATE, and DELETE operations are performed in MySQL. Therefore, there are three types of triggers supported by MySQL: INSERT triggers, UPDATE triggers, and DELETE triggers.

(1) INSERT trigger

Triggers that respond before or after the INSERT statement is executed.

Use INSERT triggers need to pay attention to the following points:

  • Within the INSERT trigger code, a virtual table named NEW can be referenced to access the inserted row.
  • In the BEFORE INSERT trigger, NEW contains the value 0 before the INSERT is executed, and the new automatically generated value after the INSERT is executed.
  • 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

Triggers that respond before or after the UPDATE statement is executed.

Note the following points when using UPDATE triggers:

  • 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 is executed.

  • In the BEFORE UPDATE trigger, the value in NEW may also be updated, that is, it is allowed to change the value that will be used in the UPDATE statement (as long as it has the corresponding operation authority). The values ​​in OLD are all 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, AFTER type triggers will not be allowed.

(3) DELETE trigger

Triggers that respond before or after the DELETE statement is executed.

Need to pay attention to the following points when using DELETE triggers:

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

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

If for a transactional table, if the trigger fails, and the resulting entire statement fails, all changes performed by the statement will be rolled back;

For non-transactional tables, this type of rollback cannot be performed, and even if the statement fails, any changes made before the failure are still valid.

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

Only when the BEFORE trigger and row operation have been successfully executed, MySQL will execute the AFTER trigger.

Two, create a trigger ( CREATE TRIGGER )

A trigger is a database object related to a MySQL data table, which is triggered when the defined conditions are met, and executes the set of statements defined in the trigger. This feature of triggers can assist applications to ensure data integrity on the database side.

grammar:

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

Syntax description:

(1) Trigger name The name of the trigger. The trigger must have a unique name in the current database. If you want to create in a particular database, the name of the database should be added in front of the name.

(2) INSERT | UPDATE | DELETE trigger event, used to specify the type of statement that activates the trigger.

Note: The execution time of the three triggers is as follows.

INSERT: The trigger is 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: The trigger is activated when a row of data is deleted from the table, such as DELETE and REPLACE statements.

UPDATE: The 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 triggered, means that the trigger is triggered 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) The table name is the name of the table associated with the trigger. This table must be a permanent table, and the trigger cannot be associated with a temporary table or view. The trigger will only be activated when a trigger event occurs on this table. The same table cannot have two triggers with the same trigger 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. The trigger action must be activated for each row affected by the trigger event. For example, when using the INSERT statement to insert multiple rows of data into a table, the trigger will execute the corresponding trigger action for each row of data insertion.

Note: Each table supports BEFORE and AFTER of INSERT, UPDATE and DELETE, so each table supports up to 6 triggers. Only one trigger per event per table is allowed at a time. A single trigger cannot be associated with multiple events or multiple tables.

//Create the table needed for the following example

mysql> create table goods
    -> (g_id int primary key,
    -> g_name varchar(22) not null,
    -> quantity int
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql>  create table orders
    ->     (
    ->     o_id int primary key,
    ->     g_id int,
    ->     counts int
    ->     );
Query OK, 0 rows affected (0.01 sec)
mysql> insert into goods values
    -> (1,"foods",100),
    -> (2,"computer",100),
    -> (3,"closth",100);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from goods;
+------+----------+----------+
| g_id | g_name   | quantity |
+------+----------+----------+
|    1 | foods    |      100 |
|    2 | computer |      100 |
|    3 | closth   |      100 |
+------+----------+----------+
3 rows in set (0.00 sec)
mysql> desc orders;
+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| o_id   | int(11) | NO   | PRI | NULL    |       |
| g_id   | int(11) | YES  |     | NULL    |       |
| counts | int(11) | YES  |     | NULL    |       |
+--------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Example 1 Create an after insert trigger
to trigger the update of the goods table content when inserting data in the orders table.

mysql> delimiter ##
mysql> create trigger test1
    -> after insert
    -> on orders for each row
    -> begin
    -> update goods set quantity=quantity-new.counts where g_id=new.g_id;
    -> end ##
Query OK, 0 rows affected (0.00 sec)
#new.counts是指orders表中,新插入数据中counts的值
mysql> delimiter ;

//Verify insert data into the orders table

mysql> select * from goods;
+------+----------+----------+
| g_id | g_name   | quantity |
+------+----------+----------+
|    1 | foods    |      100 |
|    2 | computer |      100 |
|    3 | closth   |      100 |
+------+----------+----------+
3 rows in set (0.00 sec)

mysql> insert into orders values(1,3,10);
Query OK, 1 row affected (0.00 sec)

mysql> select * from goods;
+------+----------+----------+
| g_id | g_name   | quantity |
+------+----------+----------+
|    1 | foods    |      100 |
|    2 | computer |      100 |
|    3 | closth   |       90 |
+------+----------+----------+
3 rows in set (0.00 sec)

Example 2 Create an after delete trigger
and execute a trigger to update the goods table when data is deleted in the orders table

mysql> delimiter ##
mysql> create trigger test2
    -> after delete
    -> on orders for each row
    -> begin
    -> update goods set quantity=quantity+old.counts where g_id=old.g_id;
   -> end ##
mysql> delimiter ;
#old.counts是指orders表中删除的counts列值

//Verify to delete the data in the orders table

mysql> select * from goods;
+------+----------+----------+
| g_id | g_name   | quantity |
+------+----------+----------+
|    1 | foods    |      100 |
|    2 | computer |      100 |
|    3 | closth   |       80 |
+------+----------+----------+
3 rows in set (0.00 sec)

mysql> select * from orders;
+------+------+--------+
| o_id | g_id | counts |
+------+------+--------+
|    1 |    3 |     10 |
|    2 |    3 |     10 |
+------+------+--------+
2 rows in set (0.00 sec)

mysql> delete from orders where o_id=1;
Query OK, 1 row affected (0.00 sec)

mysql> select * from goods;
+------+----------+----------+
| g_id | g_name   | quantity |
+------+----------+----------+
|    1 | foods    |      100 |
|    2 | computer |      100 |
|    3 | closth   |       90 |
+------+----------+----------+
3 rows in set (0.00 sec)

Example 3 Create an after update trigger

mysql> delimiter ##
mysql> create trigger test3
    -> after update 
    -> on orders for each row
    -> begin
    -> update goods set quantity=quantity-(new.counts-old.counts) where g_id=new.g_id;
    -> end ##
Query OK, 0 rows affected (0.00 sec)
#new.counts是指update更新后的值
#old.counts是指update更新前的值
mysql> delimiter ;

//verification

mysql> select * from goods;
+------+----------+----------+
| g_id | g_name   | quantity |
+------+----------+----------+
|    1 | foods    |      100 |
|    2 | computer |      100 |
|    3 | closth   |       90 |
+------+----------+----------+
3 rows in set (0.00 sec)

mysql> select * from orders;
+------+------+--------+
| o_id | g_id | counts |
+------+------+--------+
|    2 |    3 |     10 |
+------+------+--------+
1 row in set (0.00 sec)

mysql> update orders set counts=5 where o_id=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from orders;
+------+------+--------+
| o_id | g_id | counts |
+------+------+--------+
|    2 |    3 |      5 |
+------+------+--------+
1 row in set (0.00 sec)

mysql> select * from goods;
+------+----------+----------+
| g_id | g_name   | quantity |
+------+----------+----------+
|    1 | foods    |      100 |
|    2 | computer |      100 |
|    3 | closth   |       95 |
+------+----------+----------+
3 rows in set (0.00 sec)

New refers to the value after update, and old refers to the value before update as follows:

+------+------+--------+-------+
| o_id | g_id | counts | price |
+------+------+--------+-------+
|    1 |    3 |     10 |  50.5 |
|    2 |    3 |     10 |  50.5 |
|    3 |    3 |     10 |  50.5 |
|    4 |    3 |      2 |  50.5 | old     counts更新前是2
+------+------+--------+-------+

+------+------+--------+-------+
| o_id | g_id | counts | price |
+------+------+--------+-------+
|    1 |    3 |     10 |  50.5 |
|    2 |    3 |     10 |  50.5 |
|    3 |    3 |     10 |  50.5 |         counts更新后是5
|    4 |    3 |      5 |  50.5 | new

Three, view, modify, delete triggers

1. View triggers
(1) To view the existing triggers in the database

mysql> show triggers\G

(2) View trigger details

mysql> show create trigger test1\G
*************************** 1. row ***************************
               Trigger: test1
              sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
SQL Original Statement: CREATE DEFINER=`root`@`localhost` trigger test1
     after insert
     on orders for each row
     begin
     update goods set quantity=quantity-new.counts where g_id=new.g_id;
     end
  character_set_client: utf8
  collation_connection: utf8_general_ci
    Database Collation: utf8_general_ci
               Created: 2020-12-27 22:16:49.86
1 row in set (0.00 sec)

2. Modify the trigger.
Modify the trigger by deleting the original trigger and then creating a new trigger with the same name. The basic syntax is the same as other MySQL database objects.

3. Delete the trigger

mysql> drop trigger test1;
Query OK, 0 rows affected (0.00 sec)

Guess you like

Origin blog.csdn.net/weixin_45310323/article/details/111740885