我们如何为相同的触发事件和动作时间创建多个MySQL触发?
MySQL5.7.2+允许我们在一个表中为同一事件和动作时间创建多个触发器。事件发生时,两个触发器将顺序激活。可以借助示例来理解-
示例
在此示例中,我们为同一事件创建多个触发器,例如“更新前”。触发器的名称为“Studentdetail_before_update”和“Studentdetail_before_update2”。事件发生时,它们将顺序激活。我们正在具有以下数据的表'Student_detail'上创建这些触发器-
mysql> Select * from Student_detail; +-----------+-------------+------------+ | Studentid | StudentName | address | +-----------+-------------+------------+ | 100 | Gaurav | Delhi | | 101 | Raman | Shimla | | 103 | Rahul | Jaipur | | 104 | Ram | Chandigarh | | 105 | Mohan | Chandigarh | +-----------+-------------+------------+ 5 rows in set (0.06 sec) mysql> Delimiter //
现在,借助以下查询,我们将创建第一个触发器,该触发器将由与前面相同的查询创建。
mysql> Create Trigger studentdetail_before_update -> BEFORE UPDATE -> ON Student_detail -> FOR EACH ROW -> BEGIN -> DECLARE AUSER Varchar(40); -> SELECT USER() into AUSER; ->INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER); -> END; // mysql> Update student_detail SET Address = 'Ludhiana' Where studentName = 'Ram'; Rows matched: 1 Changed: 1 Warnings: 0
调用上面创建的触发器后,我们得到以下结果-
mysql> Select * from student_detail_updated; +-----------+---------------------+----------------+ | studentid | Updated_date | Updated_by | +-----------+---------------------+----------------+ | 104 | 2017-11-22 16:17:16 | root@localhost | +-----------+---------------------+----------------+ 1 row in set (0.00 sec)
现在,可以如下创建相同事件和动作时间的第二个触发器:
mysql> Create Trigger studentdetail_before_update2 -> BEFORE UPDATE -> ON Student_detail -> FOR EACH ROW FOLLOWS studentdetail_before_update -> BEGIN -> DECLARE AUSER Varchar(40); -> SELECT USER() into AUSER; -> INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER); -> END; //
由于我们正在使用关键字“FOLLOWS”,因此上述触发将在第一个触发后激活。
mysql> Update Student_detail SET Address = 'Patiala' WHERE studentname = 'Mohan'; Rows matched: 1 Changed: 1 Warnings: 0
现在,当我们更新该值时,以下结果集显示了同一事件和动作时间的两行。第二行代表studentdetail_before_update触发器之后的值,第三行代表studentdetail_before_update2触发器之后的值。
mysql> Select * from student_detail_updated; +-----------+---------------------+----------------+ | studentid | Updated_date | Updated_by | +-----------+---------------------+----------------+ | 104 | 2017-11-22 16:17:16 | root@localhost | | 105 | 2017-11-22 16:19:28 | root@localhost | | 105 | 2017-11-22 16:19:28 | root@localhost | +-----------+---------------------+----------------+ 3 rows in set (0.00 sec)