MySQL case combat--MySQL trigger

Preface

This environment is based on Centos 7.8 system to build MySQL-5.7.14 for
specific construction, please refer to MySQL-5.7.14 environment construction

It is often necessary to perform a join query on the emp and dept tables, each time the tables are joined, and the same string of statements are written. At the same time, because the salary queue data is more sensitive, external requirements are not visible.
In this way, we can complete by creating a view


1. What is a trigger

Trigger (trigger) is a special stored procedure, its execution is not called by the program, nor is it started manually, but triggered by events.
When an operation (insert, delete, update) is performed on a table, it will be activated for execution. Triggers are often used to strengthen data integrity constraints and business rules.

For example, when a student's information is added to the student table, the total number of students should be changed at the same time. Therefore, a trigger can be created for the student table, and each time a student record is added or deleted, a calculation operation of the total number of students is performed to ensure the consistency between the total number of students and the number of records.

Trigger (trigger) is a special stored procedure, the difference is that the execution of the stored procedure needs to be called by the CALL statement,
and the execution of the trigger does not need to be called by the CALL statement or manually started, as long asWhen a predefined event occurs, it will be automatically called by MySQL.
The advantages of the trigger program are as follows:

  • The execution of the trigger program is automatic. It will be executed immediately after making corresponding changes to the data of the trigger program related table.
  • The trigger can cascade and modify other tables through related tables in the database.
  • The trigger program can implement more complex checks and operations than FOREIGN KEY constraints and CHECK constraints.

2. Trigger actual case

1. Multiple tables for students

Information synchronization and new (add, delete)
create trigger

Prepare two tables: student, student_total.
When student information is added or deleted in the student table, the statistics of student_total are also updated

# 创建student
mysql> create table student
    -> (id int unsigned auto_increment primary key,
    -> name varchar(50));
    
# 创建student_total
mysql> create table student_total(total int);

# 两张表中分别插入数据
mysql> insert into student(name) values('z3');
mysql> insert into student_total values(1);

mysql> select * from student;
+----+------+
| id | name |
+----+------+
|  1 | z3   |
+----+------+
1 row in set (0.00 sec)

mysql> select * from student_total;
+-------+
| total |
+-------+
|     1 |
+-------+
1 row in set (0.00 sec)

# 创建学生信息增加 触发器
mysql> \d $$
mysql> create trigger student_insert after insert
    -> on student for each row
    -> begin
    ->   update student_total set total=total+1;
    -> end$$
mysql> \d ;

# 创建学生信息删除 触发器
mysql>  \d $$
mysql>  create trigger student_delete after delete
    ->  on student for each row
    ->  begin
    ->    update student_total set total=total-1;
    ->  end$$
mysql> \d ;

# 增加学生时
mysql> insert into student(name)
    -> values('l4');
mysql> select * from student;
+----+------+
| id | name |
+----+------+
|  1 | z3   |
|  2 | l4   |
+----+------+
2 rows in set (0.00 sec)

mysql> select * from student_total;
+-------+
| total |
+-------+
|     2 |
+-------+
1 row in set (0.00 sec)

# 删除学生时
mysql> delete from student
    -> where id=1;
mysql> select * from student;
+----+------+
| id | name |
+----+------+
|  2 | l4   |
+----+------+
1 row in set (0.00 sec)

mysql> select * from student_total;
+-------+
| total |
+-------+
|     1 |
+-------+
1 row in set (0.00 sec)

View the created trigger

# 查看创建的触发器
mysql> show triggers\G
*************************** 1. row ***************************
             Trigger: student_insert
               Event: INSERT
               Table: student
           Statement: begin
  update student_total set total=total+1;
end
              Timing: AFTER
             Created: 2021-02-03 15:05:38.49
            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
             Definer: root@localhost
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
*************************** 2. row ***************************
             Trigger: student_delete
               Event: DELETE
               Table: student
           Statement: begin
   update student_total set total=total-1;
 end
              Timing: AFTER
             Created: 2021-02-03 15:21:11.06
            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
             Definer: root@localhost
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
2 rows in set (0.00 sec)


mysql> select * from information_schema.triggers where TRIGGER_NAME='student_insert' or TRIGGER_NAME='student_delete'\G
*************************** 1. row ***************************
           TRIGGER_CATALOG: def
            TRIGGER_SCHEMA: db
              TRIGGER_NAME: student_insert
        EVENT_MANIPULATION: INSERT
      EVENT_OBJECT_CATALOG: def
       EVENT_OBJECT_SCHEMA: db
        EVENT_OBJECT_TABLE: student
              ACTION_ORDER: 1
          ACTION_CONDITION: NULL
          ACTION_STATEMENT: begin
  update student_total set total=total+1;
end
        ACTION_ORIENTATION: ROW
             ACTION_TIMING: AFTER
ACTION_REFERENCE_OLD_TABLE: NULL
ACTION_REFERENCE_NEW_TABLE: NULL
  ACTION_REFERENCE_OLD_ROW: OLD
  ACTION_REFERENCE_NEW_ROW: NEW
                   CREATED: 2021-02-03 15:05:38.49
                  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
                   DEFINER: root@localhost
      CHARACTER_SET_CLIENT: utf8
      COLLATION_CONNECTION: utf8_general_ci
        DATABASE_COLLATION: utf8_general_ci
*************************** 2. row ***************************
           TRIGGER_CATALOG: def
            TRIGGER_SCHEMA: db
              TRIGGER_NAME: student_delete
        EVENT_MANIPULATION: DELETE
      EVENT_OBJECT_CATALOG: def
       EVENT_OBJECT_SCHEMA: db
        EVENT_OBJECT_TABLE: student
              ACTION_ORDER: 1
          ACTION_CONDITION: NULL
          ACTION_STATEMENT: begin
   update student_total set total=total-1;
 end
        ACTION_ORIENTATION: ROW
             ACTION_TIMING: AFTER
ACTION_REFERENCE_OLD_TABLE: NULL
ACTION_REFERENCE_NEW_TABLE: NULL
  ACTION_REFERENCE_OLD_ROW: OLD
  ACTION_REFERENCE_NEW_ROW: NEW
                   CREATED: 2021-02-03 15:21:11.06
                  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
                   DEFINER: root@localhost
      CHARACTER_SET_CLIENT: utf8
      COLLATION_CONNECTION: utf8_general_ci
        DATABASE_COLLATION: utf8_general_ci
2 rows in set (0.00 sec)

Delete trigger

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

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

mysql> show triggers\G
Empty set (0.00 sec)

2. Synchronous update of multi-table information (add, update, delete)

# 创建tb1、tb2表
mysql> create table tb1
    -> (id int primary key auto_increment,
    -> name varchar(50),
    -> gender enum('男','女') default '男',
    -> age int);

mysql> create table tb2
    -> (id int primary key auto_increment,
    -> name varchar(50),
    -> salary double(10,2)
    -> );


# 分别创建插入、更新、删除的触发器
mysql> create trigger tb1_after_insert
    -> after insert
    -> on tb1 for each row
    -> begin
    ->   insert into tb2(name,salary) values(new.name,8000);
    -> end$$

mysql> create trigger tb1_after_update
    -> after update
    -> on tb1 for each row
    -> begin
    ->   update tb2 set name=new.name where name=old.name;
    -> end$$

mysql> create trigger tb1_after_delete
    -> after delete 
    -> on tb1 for each row
    -> begin
    ->   delete from tb2 where name=old.name;
    -> end$$

#

# 测试
---tb1插入三条记录
mysql> insert into tb1(name,age) values('张三','16');
mysql> insert into tb1(name,age) values('李四','22');
mysql> insert into tb1(name,age) values('王五','32');

---tb1、tb2均插入信息
mysql> select * from tb1;
+----+--------+--------+------+
| id | name   | gender | age  |
+----+--------+--------+------+
|  1 | 张三   ||   16 |
|  2 | 李四   ||   22 |
|  3 | 王五   ||   32 |
+----+--------+--------+------+
3 rows in set (0.00 sec)

mysql> select * from tb2;
+----+--------+---------+
| id | name   | salary  |
+----+--------+---------+
|  1 | 张三   | 8000.00 |
|  2 | 李四   | 8000.00 |
|  3 | 王五   | 8000.00 |
+----+--------+---------+
3 rows in set (0.00 sec)

# 修改id=2的学生name
mysql> update tb1
    -> set name='老六'
    -> where id=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from tb1;
+----+--------+--------+------+
| id | name   | gender | age  |
+----+--------+--------+------+
|  1 | 张三   ||   16 |
|  2 | 老六   ||   22 |
|  3 | 王五   ||   32 |
+----+--------+--------+------+
3 rows in set (0.00 sec)

mysql> select * from tb2;
+----+--------+---------+
| id | name   | salary  |
+----+--------+---------+
|  1 | 张三   | 8000.00 |
|  2 | 老六   | 8000.00 |
|  3 | 王五   | 8000.00 |
+----+--------+---------+
3 rows in set (0.00 sec)

mysql> delete from tb1
    -> where id=3;
Query OK, 1 row affected (0.00 sec)

mysql> select * from tb1;
+----+--------+--------+------+
| id | name   | gender | age  |
+----+--------+--------+------+
|  1 | 张三   ||   16 |
|  2 | 老六   ||   22 |
+----+--------+--------+------+
2 rows in set (0.01 sec)

mysql> select * from tb2;
+----+--------+---------+
| id | name   | salary  |
+----+--------+---------+
|  1 | 张三   | 8000.00 |
|  2 | 老六   | 8000.00 |
+----+--------+---------+
2 rows in set (0.00 sec)

Guess you like

Origin blog.csdn.net/XY0918ZWQ/article/details/113606122