Lecture 68: The core concepts of MySQL triggers and common trigger type application cases

1. The concept of trigger

Triggers are database objects related to the data in the table. When the data in the table generates operations such as inster, update, and delete, triggers can be used to complete the corresponding operations before or after these actions, such as inserting into the table. A piece of data, after inserting the data, complete some operations through triggers.

Many SQL statement sets are defined in triggers. When the action of executing the trigger is met, the SQL statements in the trigger will be executed.

Triggers can assist applications in ensuring data integrity, logging, data verification and other operations on the database side. The most typical example of a trigger is an operation log that records data in a table. For example, when a piece of data is added, it is executed The logic in the trigger records the data content inserted this time into a log table. When the data in the table is modified, the content before and after the data modification is recorded in the log table through the trigger, even if it is deleted by mistake. , data can also be quickly restored through the log table, and user behavior can also be recorded.

You can use triggers to perform a function similar to the recycle bin. When a DELETE statement is generated, the original data is written to another table. This table is the recycle bin.

There are two category names in the trigger used to refer to the record content after changes in the trigger:

  • OLD: Record the data content before the trigger changes, that is, the old data content.
    • For example, if we set a trigger for the update operation, old will record the data content before and after the trigger changes. Through old, you can refer to the data content before the update modification.
  • NEW: Record the data content after the trigger changes, that is, the new data content.
    • For example, the update trigger can reference the data content before update through old. Similarly, the data content after update can be referenced through new.

Common trigger types:

  • INSERT type trigger
    • In an INSERT type trigger, we can reference the newly added data content through the NEW alias.
  • UPDATE type trigger
    • In UPDATE type triggers, we can use OLD to reference the content before the data is modified, and use NEW to reference the content after the data is modified.
  • DELETE type trigger
    • In a DELEET type trigger, we can refer to the deleted data content through OLD.

MySQL only supports row-level triggers.

2. Syntax structure of trigger operation

Create trigger

CREATE TRIGGER 触发器名称
BEFORE/AFTER INSERT/UPDATE/DELETE				#BEFORE数据变动之前 AFTER数据变动之后 INSERT/UPDATE/DELETE表示触发器类型
ON 要对那张表设置触发器 FOR EACH ROW	#行级触发器		
BEGIN
	SQL语句
END

View triggers

SHOW TRIGGERS

delete

DROP TRIGGER 触发器名称

3. Typical application cases of various types of triggers

3.1. Requirement description and implementation ideas

Use triggers to monitor the xscjb table, and record the changes in the form of logs to the xscjb_logs table for three types of operations: addition, deletion, and modification of data in the table.

We need to log all three types of additions, deletions, and modifications of data in the table, so we need to define a trigger for each of these three types of operations.

Implementation ideas:

  • First define an xscjb_logs table to record additions, deletions, and changes to the xscjb table.
  • Then define triggers for the three operations of addition, deletion and modification. The execution of the trigger must be executed after addition, deletion and modification.
  • Finally, define the SQL statement in the trigger, and write the content before and after the table data change to the log table through the insert statement. The content before the data change can be obtained through old.字段 , the content after the data change can be obtained through new.字段.

The trigger for inserting data only needs to record the content log of new data through the new alias.

The trigger for updating data needs to record the data content before the update through old, and record the data content after the update through new, both of which are written to the log table.

The trigger for deleting data only needs to use old to record the content before the data is deleted.

3.2. Create log table

These fields can be defined in the log table:

1) Operation type: record what type of operation the log was triggered for, such as insert.

2) Operation time: Record the execution time of data changes,

3) The changed data’s primary key content in the original table: Record the changed data’s content in the primary key field of the original table.

4) Log content: Record the content before and after data changes.

create table xscjb_logs(
	id int not null auto_increment,
    oper_type varchar(10) not null comment '操作类型',
    oper_time datetime not null comment '操作时间',
    data_id int not null comment '变动的数据在原表的主键id',
    oper_log varchar(500) comment '数据变动前后的内容',
    primary key (id)
) 

3.3.INSERT type triggers

First define a data insertion trigger. When data is inserted into the table, the inserted data is recorded in the log table through an INSERT type trigger.

1) Create a trigger

create trigger xscjb_trigger_insert
after insert on xscjb for each row
begin
	insert into xscjb_logs 
	(id,oper_type,oper_time,data_id,oper_log) 
	values (
		null,
		'insert',
		now(),
		new.xh,
		concat('插入的数据内容为:xh=',new.xh,',xm=',new.xm,',ywcj=',new.ywcj,',sxcj=',new.sxcj,',yycj=',new.yycj)
	);
end;

2) The meaning of each statement in the trigger

create trigger xscjb_trigger_insert
after insert on xscjb for each row			#after表示数据变动之后执行触发器,insert表示是插入类型的触发器,当表中数据插入完成后再执行触发器,针对xscjb的触发器
begin
			#整个触发器中只有一条SQL,那就是将变动的数据插入到日志表中
	insert into xscjb_logs 				
	(id,oper_type,oper_time,data_id,oper_log) 			#为日志表中每一个字段都写入内容
	values (
		null,				#id字段不用写,id字段是主键,并且自增,无需填写内容
		'insert',			#操作类型字段填写insert即可,表示这是INSTER触发器产生的日志
		now(),				#操作时间字段可以通过now函数自动填写当前的日期时间
		new.xh,				#data_id字段要记录数据在原表的主键字段值,数据变动之后的内容都记录在new别名中,当然也可以使用old,但是insert语句没有old别名,因此我们可以通过引用new别名+指定的字段来读取数据变动后,该字段的内容,将读取到的主键内容写入到data_id字段
		concat('插入的数据内容为:xh=',new.xh,',xm=',new.xm,',ywcj=',new.ywcj,',sxcj=',new.sxcj,',yycj=',new.yycj)
 			#操作日志字段主要记录数据变动前后的内容,由于是inster类型的触发器,只记录数据变动后新增的内容,作为日志内容即可,通过concat字符串拼接函数将内容形成一段话,然后将变动的每个字段值通过new别名进行引用,就可以拿到数据变动后的新内容
	);	
end;

3) Write data to the xscjb table and observe whether there is data generated in the log table

To be more intuitive, multiple pieces of data can be written.

insert into xscjb values (NULL,'小江','88','77','66');

When data is inserted into the xscjb table, the log table will generate the corresponding inster log through the trigger. In the data_id field, you can see that the data has changed, and in the oper_log field, you can see the specific data change actions and changes. data content.

image-20220617234325902

3.4.UPDATE type triggers

The INSTER type trigger has been defined. When data is generated, the generated data content and actions will be recorded in the log table. Let's define the UPDATE type trigger. When the data changes, the data will be updated. The contents before and after are recorded in the log table.

1) Create a trigger

create trigger xscjb_trigger_update 
after update on xscjb for each row
begin
	insert into xscjb_logs 
	(id,oper_type,oper_time,data_id,oper_log) 
	values (
		null,
		'update',
		now(),
		old.xh,
		concat('更新前的数据内容:xh=',old.xh,',xm=',old.xm,',ywcj=',old.ywcj,',sxcj=',old.sxcj,',yycj=',old.yycj,'  更新后的数据内容:xh=',new.xh,',xm=',new.xm,',ywcj=',new.ywcj,',sxcj=',new.sxcj,',yycj=',new.yycj)
	);
end;

2) The meaning of each statement in the trigger

The syntax structure of triggers is the same as that of INSERT type triggers, except that a few keywords have been changed and more detailed content has been added to the log content.

create trigger xscjb_trigger_update 
after update on xscjb for each row			#update类型的触发器要将第二个关键字设置为update
begin
	insert into xscjb_logs 
	(id,oper_type,oper_time,data_id,oper_log) 
	values (
		null,
		'update',						#操作类型改为update
		now(),
		old.xh,				#这里要记录原始数据的主键值,由于是update类型,面向的是旧数据,因此通过old别名获取数据的主键值
		concat('更新前的数据内容:xh=',old.xh,',xm=',old.xm,',ywcj=',old.ywcj,',sxcj=',old.sxcj,',yycj=',old.yycj,'  更新后的数据内容:xh=',new.xh,',xm=',new.xm,',ywcj=',new.ywcj,',sxcj=',new.sxcj,',yycj=',new.yycj)
        #update语句会通过old别名记录更新前的数据,通过new记录更后的数据,为了方便查看,我们可以在操作日志中记录update更数据前后的数据内容,更新前通过old别名引用获取指定字段的数据,更新后通过new别名引用获取指定字段的数据
	);
end;

3) Update the data observation log table in the xscjb table

update xscjb set ywcj = '100' where xm = '小黑';

When the data in the xscjb table changes, the xscjb_trigger_update trigger writes a piece of data to the log table to record the content before and after the data update.

image-20220617235643041

3.5.DELETE type triggers

Finally, we define a DELETE type trigger. When the data in the table is deleted, the deleted data content is recorded in the log table.

1) Create a trigger

create trigger xscjb_trigger_delete
after delete on xscjb for each row
begin
	insert into xscjb_logs 
	(id,oper_type,oper_time,data_id,oper_log) 
	values (
		null,
		'delete',	
		now(),
		old.xh,
		concat('删除的数据内容:xh=',old.xh,',xm=',old.xm,',ywcj=',old.ywcj,',sxcj=',old.sxcj,',yycj=',old.yycj)
	);
end;

2) The meaning of each statement in the trigger

create trigger xscjb_trigger_delete
after delete on xscjb for each row				#delete类型的触发器要将第二个关键字设置为delete
begin
	insert into xscjb_logs 
	(id,oper_type,oper_time,data_id,oper_log) 
	values (
		null,
		'delete',					#操作类型改为delete
		now(),
		old.xh,				#这里要记录原始数据的主键值,由于是delete类型,面向的是旧数据,因此通过old别名获取数据的主键值
		concat('删除的数据内容:xh=',old.xh,',xm=',old.xm,',ywcj=',old.ywcj,',sxcj=',old.sxcj,',yycj=',old.yycj)
	);			#最后将日志内容稍加变动即可
end;

3) Delete multiple records in the data observation log table

delete from xscjb where xh > '9';

The condition for deletion is that xh is greater than 9. After the data is deleted, the deleted data will be recorded in the log table.

image-20220618000638627

Guess you like

Origin blog.csdn.net/weixin_44953658/article/details/134240227