Combat de cas MySQL - Déclencheur MySQL

Préface

Cet environnement est basé sur le système Centos 7.8 pour construire MySQL-5.7.14 pour
une construction spécifique, veuillez vous référer à la construction de l'environnement MySQL-5.7.14

Il est souvent nécessaire d'effectuer une requête de jointure sur les tables emp et dept, chaque fois que les tables sont connectées, et la même chaîne d'instructions est écrite. En même temps, les données de la file d'attente des salaires étant plus sensibles, les exigences externes sont invisible.
De cette façon, nous pouvons compléter en créant une vue


1. Qu'est-ce qu'un déclencheur

Trigger (trigger) est une procédure stockée spéciale, son exécution n'est pas appelée par le programme, ni démarrée manuellement, mais déclenchée par des événements.
Lorsqu'une opération (insertion, suppression, mise à jour) est effectuée sur une table, elle sera activée pour exécution. Les déclencheurs sont souvent utilisés pour renforcer les contraintes d'intégrité des données et les règles métier.

Par exemple, lorsque les informations d'un étudiant sont ajoutées à la table des étudiants, le nombre total d'étudiants doit être modifié en même temps. Par conséquent, un déclencheur peut être créé pour la table des étudiants, et chaque fois qu'un enregistrement d'étudiant est ajouté ou supprimé, une opération de calcul du nombre total d'étudiants est effectuée pour assurer la cohérence entre le nombre total d'étudiants et le nombre d'enregistrements.

Le déclencheur (déclencheur) est une procédure stockée spéciale, la différence est que l'exécution de la procédure stockée doit être appelée par l'instruction CALL,
et l'exécution du déclencheur n'a pas besoin d'être appelée par l'instruction CALL ou démarrée manuellement, car tant queLorsqu'un événement prédéfini se produit, il sera automatiquement appelé par MySQL.
Les avantages du programme de déclenchement sont les suivants:

  • L'exécution du programme de déclenchement est automatique. Il sera exécuté immédiatement après avoir apporté les modifications correspondantes aux données de la table associée au programme de déclenchement.
  • Le déclencheur peut mettre en cascade et modifier d'autres tables via des tables liées dans la base de données.
  • Le programme de déclenchement peut implémenter des contrôles et des opérations plus complexes que les contraintes FOREIGN KEY et CHECK.

2. Déclencher un cas réel

1. Tables multiples pour les étudiants

Synchronisation des informations et nouveau déclencheur de création (ajouter, supprimer)

Préparez deux tableaux: student, student_total.
Lorsque des informations sur les étudiants sont ajoutées ou supprimées dans la table des étudiants, les statistiques de student_total sont également mises à jour.

# 创建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)

Afficher le déclencheur créé

# 查看创建的触发器
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)

Supprimer le déclencheur

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. Mise à jour synchrone des informations multi-tables (ajout, mise à jour, suppression)

# 创建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)

Je suppose que tu aimes

Origine blog.csdn.net/XY0918ZWQ/article/details/113606122
conseillé
Classement