Trigger-MySQL

What is a trigger?

It can be understood as a button. When you click this button, it will perform some other operations, such as opening a window. can

An event-driven

 

The concept of triggers

In actual development, we often encounter such situations:

When we perform data operations on a table, we need to perform corresponding operations on other tables synchronously. Under normal circumstances, if we use sql statements to update, we will need to perform multiple operation statements!

For example, in some chess and card games, when the player recharges gold coins, the gold coins in the player table database increase, and at the same time, the player's agent will get the corresponding commission and be included in the agent's income, that is, the commission record field of the agent database table will also Synchronization Update.

 

And the above scenario, we can easily use triggers to achieve!

Trigger (TRIGGER) is triggered by an event. These events include INSERT statements, UPDATE statements, and DELETE statements. When the database system executes these events, it will activate the trigger to perform the corresponding operation. MySQL has supported triggers since version 5.0.2.

Through the study of this chapter, we will understand the meaning and function of triggers, how to create triggers, view triggers and delete triggers. At the same time, you can understand the execution of triggers for various events.

Create trigger 

The creation of triggers in MySQL is achieved through the SQL statement CREATE TRIGGER, and its syntax is as follows:

       CREATE trigger trigger_name BEFORE|AFTER trigger_EVENT     

       ON TABLE_NAME FOR EACH ROW trigger_STMT               

In the above statement, the parameter trigger_name represents the name of the trigger to be created;

The parameters BEFORE and AFTER specify the trigger execution time, the former executes the trigger statement before the trigger event, and the latter executes the trigger statement after the trigger event;

The parameter trigger_EVENT indicates the trigger event, that is, the trigger execution conditions, including DELETE , INSERT and UPDATE statements; the parameter TABLE_NAME indicates the name of the operation table that triggered the event; the parameter FOR EACH ROW indicates that the operation on any record will trigger the trigger when the trigger event is satisfied;

The parameter trigger_STMT represents the statement executed after the trigger is activated. If you want to reference the fields in the update record in the execution statement, for the INSERT statement, only NEW is legal, which means the currently inserted record; for the DELETE statement, only OLD is legal, which means the current deleted record; and the UPDATE statement can be combined with NEW (After update) and OLD (before update) are used at the same time.

Note: You cannot create a trigger with the same name. In addition, for a given table with the same trigger action time and event, there cannot be two triggers. Therefore, for experienced users, before creating a trigger, you need to check whether the trigger of the identifier and related events of the trigger already exist in MySQL.

[Demo] Execute the SQL statement CREATE TRIGGER, there are two table objects in the database school: student table student and class table class. When creating a trigger to insert a record into the student table, the number of people in the class table will be updated after the insert , When we delete a record of a student, the number of people in the class table will be updated after deletion. The specific steps are as follows:

mysql>   use school;    #Select database school                                             

mysql>  CREATE TABLE class (                                                        

  `id` int NOT NULL AUTO_INCREMENT,                                                

  `name` varchar(128) DEFAULT NULL,                                                 

  `teacher` varchar(64) DEFAULT NULL,                                                  

  `count`  int DEFAULT 0,                                                                 

  UNIQUE KEY `id` (`id`)                                                               

);   #Create class table class                                                                  

mysql>  insert into class values(101,'Mengxin Class One','Martin', 0),(102,'Mengxin Class Two','Rock', 0),(103,'Mengxin Class Three', 'Janny', 0); #Create   grade table grade                                                 

mysql>  CREATE TABLE `student` (                                                    

  `id` int NOT NULL AUTO_INCREMENT UNIQUE,                                                            

  `name` varchar(64) DEFAULT NULL,                                                  

  `class_id` int DEFAULT NULL,                                                        

  `sex` enum('F','M') DEFAULT NULL                                                   

);                                                                                     

mysql>  create trigger tri_insert_student after insert on student for each row update class set count=count+1 where class.id = NEW.class_id; #Create    trigger, increase the number of new students by 1      

                                                                                        

mysql> insert into student values(1,'小花',101,'M'),(2,'小红',102,'F'),(3,'小军',102,'F'), (4,'小白',101,'F');   #Insert multiple records                                                                   

mysql> select count  from class  ; #Query the number of class tables                                      

mysql> create trigger tri_delete_student after delete on student for each row update class set count=count-1 where id = OLD.class_id; #Create trigger, delete student class number minus 1                 

 

Trigger contains multiple execution statements

       CREATE   trigger trigger_name BEFORE|AFTER trigger_EVENT     

       ON TABLE_NAME FOR EACH ROW                                 

           BEGIN                                                        

            trigger_STMT                                                 

           END                                                           

在上述语句中,比“只有一条执行语句的触发器”语法多出来两个关键字BEGIN和END,在这两个关键字之间是所要执行的多个执行语句的内容,执行语句之间用分号隔开。

在MySQL中,一般情况下用“;”符号作为语句的结束符号,可是在创建触发器时,需要用到“;”符号作为执行语句的结束符号。为了解决该问题,可以使用关键字DELIMITER语句。例如,“DELIMITER $$”可以将结束符号设置成“$$”。

mysql>  use school;   #选择数据库school         

mysql>  create table grade(id int UNIQUE AUTO_INCREMENT,  math tinyint unsigned, chinese tinyint unsigned, english tinyint unsigned);       #创建成绩表 grade   

mysql> insert into grade values(1, 80, 87, 91),(2, 72, 64, 89),(3, 54, 69, 87),(4, 78, 79, 89);  #插入多条记录                                      

mysql> DELIMITER $$                                                                                

mysql> create trigger tri_delete_student after delete on student for each row

        BEGIN                                    

         Delete from grade where id = OLD.id;  #删除成绩表中的记录                                                        

         update class set count=count-1 where id = OLD.class_id; #更新班级表中的记录   

         END;                                    

         $$                                       

         DELIMITER ;                            

查看触发器

  1. SHOW TRIGGERS语句查看触发器

那么如何查看MySQL软件中已经存在的触发器呢?在MySQL软件中查看已经存在的触发器,通过SQL语句SHOW TRIGGERS来实现,其语法形式如下,执行上面的SQL语句,执行结果如图9-10所示。

     SHOW TRIGGERS ;  

通过图9-10的执行结果可以发现,执行完“SHOW TRIGGERS”语句后会显示一个列表,在该列表中会显示出所有触发器的信息。其中,参数Trigger表示触发器的名称;参数Event表示触发器的激发事件;参数Table表示触发器对象触发事件所操作的表;参数Statement表示触发器激活时所执行的语句;参数Timing表示触发器所执行的时间。

  1. 查看系统表triggers实现查看触发器

在MySQL中,在系统数据库information_schema中存在一个存储所有触发器信息的系统表triggers,因此查询该表格的记录也可以实现查看触发器功能。系统表triggers的表结构

mysql>  use information_schema;   #选择数据库information_schema                  

mysql>  select * from triggers;                                                        

mysql>  select * from triggers where trigger_name=tri_delete_student; #查询系统表triggers中的触发器                                                                  


触发器的删除

在MySQL软件中,可以通过DROP TRIGGER语句通过工具删除触发器。

在MySQL中,删除触发器可以通过SQL语句DROP TRIGGER来实现,其语法形式如下:

    DROP TRIGGER trigger_name; 

在上述语句中,参数trigger_name表示所要删除的触发器名称。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_44065088/article/details/107351387