推荐看这篇mysql 利用触发器(Trigger)让代码更简单

以及 23.3.1 Trigger Syntax and Examples

感觉有点像 Spring 里的 AOP

我们为什么需要触发器? -- 因为我们希望当某件事情发生的时候另外一些事情自动发生。。

例如 在向某张表插入数据的时候,同时向另外一张表插入数据。

“向某张表插入数据” 就是事件(导火线),而“向另外一张表插入数据” 就是我们希望自动发生的事情(被触发的事情)。

可是为什么不自己手动“ 先向某表插入数据,再向另外一张表插入数据”呢?

个人觉得,有两个理由促使我们这么做:

  1. 实现某种业务逻辑,就像下了订单一定要减库存对吧? 但是这个活是上层应用程序做还是数据库做是个问题。
  2. 关注点分离。触发事件可以是一些琐碎、业务无关的安全性检查之类的,这个概念可以参考 Spring AOP

下面 COPY 几个 demo 备用。

首先是查看已存在的触发器:

SELECT * FROM information_schema.`TRIGGERS`;

删除已经存在的触发器:

DROP TRIGGER newproduct;

创建一个简单的触发器:

CREATE TRIGGER newproduct AFTER INSERT ON products
FOR EACH ROW SELECT 'Product added';

-- -  每当向 products 插入数据的时候都执行 SELECT 'Product added' ,// 原话打印

- - -- FOR EACH ROW 对于插入的每一条记录都这么做

--- --  PS. 触发器只能创建在实表上,不能创建在虚表上(视图)

-- - - - 每张表至多支持 6 个触发器 AFTER BEFORE 2 * 3 UPDATE DELETE INSERT = 6      PS. 这个有错。

-  ---我尝试了一下居然运行不出来 。。 。 所以,以上规则可能在新版本有变化。。

mysql> CREATE TRIGGER newproduct AFTER INSERT ON products
-> FOR EACH ROW SELECT 'Product added';
ERROR 1415 (0A000): Not allowed to return a result set from a trigger

关于触发器的几个注意点:

  1. 触发器不能被覆盖 override ,要修改的话,只能先删除旧的、再创建一个新的。
  2. 在 BEFORE触发器 → SQL语句 → AFTER 触发器这个执行流程中,任何一步出现错误都将不再往下执行。

关于 OLD 和 NEW 关键词

Within the trigger body, the OLD and NEW keywords enable you to access columns in the rows affected by a trigger. OLDand NEW are MySQL extensions to triggers; they are not case-sensitive.

In an INSERT trigger, only NEW.col_name can be used; there is no old row. In a DELETE trigger, only OLD.col_name can be used; there is no new row. In an UPDATE trigger, you can use OLD.col_name to refer to the columns of a row before it is updated and NEW.col_name to refer to the columns of the row after it is updated.

A column named with OLD is read only. You can refer to it (if you have the SELECT privilege), but not modify it. You can refer to a column named with NEW if you have the SELECT privilege for it. In a BEFORE trigger, you can also change its value with SET NEW.col_name = value if you have the UPDATE privilege for it. This means you can use a trigger to modify the values to be inserted into a new row or used to update a row. (Such a SET statement has no effect in an AFTERtrigger because the row change will have already occurred.)

In a BEFORE trigger, the NEW value for an AUTO_INCREMENT column is 0, not the sequence number that is generated automatically when the new row actually is inserted.

触发更多语句

By using the BEGIN ... END construct, you can define a trigger that executes multiple statements.

mysql> delimiter //
mysql> CREATE TRIGGER upd_check BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END;//
mysql> delimiter ;

demo

DROP TRIGGER IF EXISTS afterDeleteStudent;
DELIMITER //
CREATE TRIGGER afterDeleteStudent
AFTER DELETE ON stu
FOR EACH ROW
BEGIN
DELETE FROM SC WHERE SC.stu_id = OLD.id;
END //
DELIMITER ;

MySQL Crash Course #17# Chapter 25. 触发器(Trigger)的更多相关文章

  1. MySQL Crash Course #09# Chapter 17. Combining Queries: UNION

    INDEX UNION Rules WHERE VS. UNION UNION VS. UNION ALL Sorting Combined Query Results UNION Rules As ...

  2. MySQL Crash Course #13# Chapter 21. Creating and Manipulating Tables

    之前 manipulate 表里的数据,现在则是 manipulate 表本身. INDEX 创建多列构成的主键 自动增长的规定 查看上一次插入的自增 id 尽量用默认值替代 NULL 外键不可以跨引 ...

  3. MySQL Crash Course #11# Chapter 20. Updating and Deleting Data

    INDEX Updating Data The IGNORE Keyword Deleting Data Faster Deletes Guidelines for Updating and Dele ...

  4. MySQL Crash Course #10# Chapter 19. Inserting Data

    INDEX BAD EXAMPLE Improving Overall Performance Inserting Multiple Rows INSTEAD OF Inserting a Singl ...

  5. MySQL Crash Course #06# Chapter 13. 14 GROUP BY. 子查询

    索引 理解 GROUP BY 过滤数据 vs. 过滤分组 GROUP BY 与 ORDER BY 之不成文的规定 子查询 vs. 联表查询 相关子查询和不相关子查询. 增量构造复杂查询 Always ...

  6. MySQL Crash Course #05# Chapter 9. 10. 11. 12 正则.函数. API

    索引 正则表达式:MySQL only supports a small subset of what is supported in most regular expression implemen ...

  7. MySQL Crash Course #04# Chapter 7. 8 AND. OR. IN. NOT. LIKE

    索引 AND. OR 运算顺序 IN Operator VS. OR NOT 在 MySQL 中的表现 LIKE 之注意事项 运用通配符的技巧 Understanding Order of Evalu ...

  8. MySQL Crash Course #21# Chapter 29.30. Database Maintenance & Improving Performance

    终于结束这本书了,最后两章的内容在官方文档中都有详细介绍,简单过一遍.. 首先是数据备份,最简单直接的就是用 mysql 的内置工具 mysqldump MySQL 8.0 Reference Man ...

  9. MySQL Crash Course #20# Chapter 28. Managing Security

    限制用户的操作权限并不是怕有人恶意搞破坏,而是为了减少失误操作的可能性. 详细文档:https://dev.mysql.com/doc/refman/8.0/en/user-account-manag ...

随机推荐

  1. 170822、解决PLSQL记录被另一个用户锁住的问题

    1.查看数据库锁,诊断锁的来源及类型: select object_id,session_id,locked_mode from v$locked_object; 或者用以下命令: select b. ...

  2. MySQL NDB集群安装配置(mysql cluster 9.4.13 installation)

    一.安装前规划 1.安装软件版本:mysql-cluster-gpl-7.4.13-linux-glibc2.5-x86_64.tar.gz 2.安装规划: 主机名 Ip地址 角色 db01 192. ...

  3. 自己封装framworks上传到应用商店报错

    参考链接: http://www.jianshu.com/p/60ac3ded34a0 http://ikennd.ac/blog/2015/02/stripping-unwanted-archite ...

  4. 疯狂java讲义 第三版 笔记

      java7新加特性: 0B010101  二进制数 int c=0B0111_1111;   数值中使用下划线分隔 switch 支持String类型   字符串常量放在常量池 String s0 ...

  5. js-之NaN和isNaN

    NaN (not is number) 不是一个数字的意思,在js中整型和浮点数都是Number类型. 除此之外,Number还有一个特殊的值,NaN. 一.可能会产生NaN值的情况 1.表达式计算, ...

  6. xshell免费下载安装使用

    下载链接:https://www.netsarang.com/zh/all-downloads/ 然后点击下载: 然后接下来这一步很关键: 点击免费授权页面,然后填完邮箱会有激活链接,然后就可以下载免 ...

  7. LightOj 1248 - Dice (III)(几何分布+期望)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1248 题意:有一个 n 面的骰子,问至少看到所有的面一次的所需 掷骰子 的 次数的期望 ...

  8. Shuffle'm Up---poj3087

    题目链接 题意:有两个字符串s1,s2:经过交叉问是否得到字符串s,不能输出-1,能就输出交叉的次数 每次重组的串都是s2开始,重新组合时,前面一半是s1,后一半s2: #include<std ...

  9. 机器学习【算法】:KNN近邻

    引言 本文讨论的kNN算法是监督学习中分类方法的一种.所谓监督学习与非监督学习,是指训练数据是否有标注类别,若有则为监督学习,若否则为非监督学习.监督学习是根据输入数据(训练数据)学习一个模型,能对后 ...

  10. Looper分析。ThreadLocal有关

    Class used to run a message loop for a thread. Threads by default do not have a message loop associa ...