MySQL高级8-触发器

MySQL,高级,触发器 · 浏览次数 : 191

小编点评

# generate content # content # insert into student_logs # update after data # delete after data # return content # content # insert into student_logs # update after data # delete after data # return content

正文

一、触发器

  触发器是与表有关的数据库对象,指在insert/update/delete之前或者之后,触发并执行触发器中定义的sql语句集合,触发器的这种特性可以协助应用在数据库端确保数据的完整性,日志记录,数据校验等操作。

使用别名old和new来引用触发器中发生变化的记录内容,这与其他的数据库是相似的,现在触发器还只支持行级触发,不支持语句级触发。

 

二、触发器类型

  • insert型触发器:new表示将要或者已经新增的数据
  • update型触发器:old表示修改之前的数据,new表示将要或已经修改后的数据
  • delete型触发器:old表示将要或者已经删除的数据

 

三、触发器语法

  3.1 创建语法

create trigger trigger_name
before/after insert/update/delete
on tb_name for each row
begin
  trigger_stmt;
end;

  3.2 查看语法

show triggers;

  3.3 删除语句

drop trigger [schema_name.] trigger_name;  -- 如果没有指定schema_name,默认为当前数据库

 

四、插入数据触发器案例

  4.1 需求:

    通过触发器记录student表的数据插入时,将变更日志插入到日志表student_logs中;

  4.2 创建 student_logs表

mysql> create table student_logs(
    -> id int primary key auto_increment,
    -> operation varchar(20) comment "操作类型,insert/update/delete",
    -> operate_time datetime comment "操作时间",
    -> operate_id int comment "操作的ID",
    -> operate_params varchar(500) comment "操作参数"
    -> )comment "student操作日志表";
Query OK, 0 rows affected (1.18 sec)

  4.3 创建插入数据触发器

mysql>delimiter &
mysql> create trigger student_insert_trigger
        -> after insert on student for each row 
        ->begin 
        ->    insert into student_logs(id,operation,operate_time,operate_id,operate_params) values (null, 'insert', now(), new.id, concat("插入的数据内容为:id=",new.id,"name=",new.name,"age=",new.age,"score=",new.score));
        ->end;
        ->&
Query OK, 0 rows affected (0.20 sec)   

    说明1:delimiter &在之前的文章中已经提到过,是将mysql中的语句终止符由“;” 改为“&”,原因是,触发器中有完整的sql语句,会包含分号,如果不改,怎无法在终端中书写完整的触发器语句

  4.4 查看创建的触发器

mysql> delimiter ;
mysql> show triggers;
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
| Trigger                | Event  | Table   | Statement                                                                                                                                                                                                                           | Timing | Created                | sql_mode                                                                                                              | Definer                           | character_set_client | collation_connection | Database Collation |
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
| student_insert_trigger | INSERT | student | begin insert into student_logs(id,operation,operate_time,operate_id,operate_params) values (null, 'insert', now(), new.id, concat("插入的数据内容为:id=",new.id,"name=",new.name,"age=",new.age,"score=",new.score)); end          | AFTER  | 2023-08-16 00:07:46.53 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | skip-grants user@skip-grants host | utf8mb4              | utf8mb4_0900_ai_ci   | utf8mb4_0900_ai_ci |
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)

    说明2:delimiter是将sql语句终止符由“&”在改为“;”

  4.5 插入验证

mysql> insert into student(id,name,age,score) values(null,"李白",30,100);
Query OK, 1 row affected (0.21 sec)

mysql> select * from student_logs;
+----+-----------+---------------------+------------+-----------------------------------------------------------+
| id | operation | operate_time        | operate_id | operate_params                                            |
+----+-----------+---------------------+------------+-----------------------------------------------------------+
|  1 | insert    | 2023-08-16 00:21:47 |          5 | 插入的数据内容为:id=5name=李白age=30score=100            |
+----+-----------+---------------------+------------+-----------------------------------------------------------+
1 row in set (0.00 sec)

    说明3:插入数据李白的信息就已经自动的在student_logs中记录

五、修改数据触发器案例

  5.1 创建修改数据触发器

mysql>delimiter &
mysql> create trigger student_update_trigger after update on student for each row begin insert into student_logs(id, operation, operate_time,operate_id,operate_params) values (null,'update',now(),new_id,concat( '更新前数据:id=',old.id,',name=',old.name,',age=',old.age,',score=',old.score,' | 更新后数据:id=',new.id, ',name=',new.name, ',age=',new.age, ',score=',new.score)); end; &
Query OK, 0 rows affected (1.86 sec)
mysql> delimiter ;

  5.2 查看创建的触发器

mysql> show triggers;
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
| Trigger                | Event  | Table   | Statement                                                                                                                                                                                                                                                                                                               | Timing | Created                | sql_mode                                                                                                              | Definer                           | character_set_client | collation_connection | Database Collation |
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
| student_insert_trigger | INSERT | student | begin insert into student_logs(id,operation,operate_time,operate_id,operate_params) values (null, 'insert', now(), new.id, concat("插入的数据内容为:id=",new.id,"name=",new.name,"age=",new.age,"score=",new.score)); end                                                                                              | AFTER  | 2023-08-16 00:07:46.53 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | skip-grants user@skip-grants host | utf8mb4              | utf8mb4_0900_ai_ci   | utf8mb4_0900_ai_ci |
| student_update_trigger | UPDATE | student | begin insert into student_logs(id, operation, operate_time,operate_id,operate_params) values (null,'update',now(),new.id,concat( '更新前数据:id=',old.id,',name=',old.name,',age=',old.age,',score=',old.score,' | 更新后数据:id=',new.id, ',name=',new.name, ',age=',new.age, ',score=',new.score)); end             | AFTER  | 2023-08-16 23:38:26.36 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | skip-grants user@skip-grants host | utf8mb4              | utf8mb4_0900_ai_ci   | utf8mb4_0900_ai_ci |
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
2 rows in set (1.16 sec)

  5.3 查看student表原始数据

mysql> select * from student;
+----+--------+------+-------+
| id | name   | age  | score |
+----+--------+------+-------+
|  1 | 张三   |   18 |    88 |
|  2 | 李四   |   21 |    83 |
|  3 | 王五   |   24 |    76 |
|  4 | 赵六   |   19 |    94 |
|  5 | 李白   |   30 |   100 |
+----+--------+------+-------+
5 rows in set (1.30 sec)

  5.4 修改student表,验证触发器

mysql> update student set age=25 where id = 5;
Query OK, 1 row affected (0.38 sec)
Rows matched: 1  Changed: 1  Warnings: 0

  5.5 查看修改后的student表和student_logs表,验证触发器

mysql> select * from student;
+----+--------+------+-------+
| id | name   | age  | score |
+----+--------+------+-------+
|  1 | 张三   |   18 |    88 |
|  2 | 李四   |   21 |    83 |
|  3 | 王五   |   24 |    76 |
|  4 | 赵六   |   19 |    94 |
|  5 | 李白   |   25 |   100 |
+----+--------+------+-------+
5 rows in set (0.00 sec)

mysql> select * from student_logs;
+----+-----------+---------------------+------------+-----------------------------------------------------------------------------------------------------------+
| id | operation | operate_time        | operate_id | operate_params                                                                                            |
+----+-----------+---------------------+------------+-----------------------------------------------------------------------------------------------------------+
|  1 | insert    | 2023-08-16 00:21:47 |          5 | 插入的数据内容为:id=5name=李白age=30score=100                                                            |
|  2 | update    | 2023-08-16 23:58:23 |          5 | 更新前数据:id=5,name=李白,age=30,score=100 | 更新后数据:id=5,name=李白,age=25,score=100                 |
+----+-----------+---------------------+------------+-----------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

  

六、删除数据触发器案例

  6.1 创建删除数据触发器

mysql>delimiter &
mysql> create trigger student_delete_trigger after delete on student for each row begin insert into student_logs(id,operation,operate_time,operate_id,operate_params) values (null,'delete',now(),old.id, concat('删除之前的数据:id=',old.id, ',name=',old.name,',age=',old.age,',score=',old.score)); end;&
Query OK, 0 rows affected (0.87 sec)

  6.2 查看触发器

mysql> show triggers;
    -> &
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
| Trigger                | Event  | Table   | Statement                                                                                                                                                                                                                                                                                                               | Timing | Created                | sql_mode                                                                                                              | Definer                           | character_set_client | collation_connection | Database Collation |
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
| student_insert_trigger | INSERT | student | begin insert into student_logs(id,operation,operate_time,operate_id,operate_params) values (null, 'insert', now(), new.id, concat("插入的数据内容为:id=",new.id,"name=",new.name,"age=",new.age,"score=",new.score)); end                                                                                              | AFTER  | 2023-08-16 00:07:46.53 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | skip-grants user@skip-grants host | utf8mb4              | utf8mb4_0900_ai_ci   | utf8mb4_0900_ai_ci |
| student_update_trigger | UPDATE | student | begin insert into student_logs(id, operation, operate_time,operate_id,operate_params) values (null,'update',now(),new.id,concat( '更新前数据:id=',old.id,',name=',old.name,',age=',old.age,',score=',old.score,' | 更新后数据:id=',new.id, ',name=',new.name, ',age=',new.age, ',score=',new.score)); end             | AFTER  | 2023-08-16 23:57:34.20 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | skip-grants user@skip-grants host | utf8mb4              | utf8mb4_0900_ai_ci   | utf8mb4_0900_ai_ci |
| student_delete_trigger | DELETE | student | begin insert into student_logs(id,operation,operate_time,operate_id,operate_params) values (null,'delete',now(),old.id, concat('删除之前的数据:id=',old.id, ',name=',old.name,',age=',old.age,',score=',old.score)); end                                                                                               | AFTER  | 2023-08-17 00:15:46.44 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | skip-grants user@skip-grants host | utf8mb4              | utf8mb4_0900_ai_ci   | utf8mb4_0900_ai_ci |
+------------------------+--------+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------+----------------------+----------------------+--------------------+
3 rows in set (0.00 sec)

  6.3 删除数据

mysql> delimiter ;
mysql> delete from student where id = 5;
Query OK, 1 row affected (0.70 sec)

  6.4 查看student表和student_logs表验证触发器

mysql> select * from student;
+----+--------+------+-------+
| id | name   | age  | score |
+----+--------+------+-------+
|  1 | 张三   |   18 |    88 |
|  2 | 李四   |   21 |    83 |
|  3 | 王五   |   24 |    76 |
|  4 | 赵六   |   19 |    94 |
+----+--------+------+-------+
4 rows in set (0.00 sec)

mysql> select * from student_logs;
+----+-----------+---------------------+------------+-----------------------------------------------------------------------------------------------------------+
| id | operation | operate_time        | operate_id | operate_params                                                                                            |
+----+-----------+---------------------+------------+-----------------------------------------------------------------------------------------------------------+
|  1 | insert    | 2023-08-16 00:21:47 |          5 | 插入的数据内容为:id=5name=李白age=30score=100                                                            |
|  2 | update    | 2023-08-16 23:58:23 |          5 | 更新前数据:id=5,name=李白,age=30,score=100 | 更新后数据:id=5,name=李白,age=25,score=100                 |
|  3 | delete    | 2023-08-17 00:18:06 |          5 | 删除之前的数据:id=5,name=李白,age=25,score=100                                                           |
+----+-----------+---------------------+------------+-----------------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)

 

与MySQL高级8-触发器相似的内容:

MySQL高级8-触发器

一、触发器 触发器是与表有关的数据库对象,指在insert/update/delete之前或者之后,触发并执行触发器中定义的sql语句集合,触发器的这种特性可以协助应用在数据库端确保数据的完整性,日志记录,数据校验等操作。 使用别名old和new来引用触发器中发生变化的记录内容,这与其他的数据库是相

[转帖]第一章 MySQL 8.0 介绍及安装配置

第一章 MySQL 8.0 介绍及安装配置 https://www.jianshu.com/p/d190c6b3520d 本课程,适合具备一定Linux运维或者开发基础的朋友,课程定级中、高级DBA。只要掌握80%,轻松助力薪资15k-25K。课程内容均来自与MySQL官网+MySQL源码。配套精品

小白也能懂的Mysql数据库索引详解

核心概念 主键索引/二级索引 聚簇索引/非聚簇索引 回表/索引覆盖 索引下推 联合索引/最左联合匹配 前缀索引 explain 一、[索引定义] 1.索引定义 在数据之外,数据库系统还维护着满足特定查找算法的数据结构,这些数据结构以某种方式引用(指向)数据,这样就可以在这些数据结构上实现高级查找算法

分享10个高级sql写法

本文主要介绍博主在以往开发过程中,对于不同业务所对应的 sql 写法进行归纳总结而来。进而分享给大家。 本文所讲述 sql 语法都是基于 MySql 8.0+ 博主github地址:http://github.com/wayn111 欢迎大家关注,点个star 一、ORDER BY FIELD()

[转帖]MySQL 8.0.19 instant add column,亿级数据秒速增加字段

一、MySQL DDL 的方法 MySQL 在大型表上的 DDL 会带来耗时较久、负载较高、额外空间占用、MDL、主从同步延时等情况。需要特别引起重视,而MySQL 的 DDL 有很多种方法。 MySQL 本身自带三种方法,分别是:copy、inplace、instant。 copy 算法为最古老的

[转帖]Keepalived如何实现Nginx高可用

https://www.jb51.net/article/266305.htm Keepalived安装可参考Mysql+Keepalived实现双主热备 Master上的keepalived.conf 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

MySQL 执行计划详解

本文从EXPLAIN分析SQL的执行计划开始,进行示例展示,并对输出结果进行解读,同时总结了EXPLAIN可产生额外的扩展信息以及EXPLAIN的估计查询性能,整篇文章基于MySQL 8.0编写,理论支持MySQL 5.0及更高版本。

MySQL高级

前言: 本篇文章是本人学习MySQL高级的笔记。 资料:《MySQL是怎样运行的》、《小林Coding-图解MySQL》、《MySQL45讲》、《尚硅谷康师傅MySQL视频》 一、基础篇 1. 什么是关系型数据库? 关系型数据库是指采用了关系模型来组织数据的数据库,其以行和列的形式存储数据,一系列的

MySQL高级1-存储引擎

一、Mysql体系结构 1.1、连接层 最上层是一个客户端和链接服务,主要完成一些类似于链接处理,授权认证,及相关的安全方案,服务器也会为安全接入的而每个客户端验证它所具有的操作权限 1.2、服务层 第二层架构主要完成大多数的核心服务功能,如SQL接口,并完成缓存的查询,SQL的分析和优化,部分内置

MySQL高级9-锁

一、简介 锁是计算机协调多个进程或线程并发访问某一资源的机制。在数据库中,除了传统的计算资源(CPU、RAM、i/O)的挣用以外,数据也是一种供许多用户共享的资源。如何保证数据并发访问的一致性,有效性是所有数据库必须解决的一个问题,锁冲突也是影响数据库并发访问性能的一个重要因素,从这个角度来说,锁对