mysql create triggers_mysql 触发器的创建

2023-11-05

CREATE TRIGGER Syntax

CREATE

[DEFINER = { user | CURRENT_USER }]

TRIGGER trigger_name trigger_time trigger_event

ON tbl_name FOR EACH ROW trigger_stmt

This statement creates a new trigger. A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. CREATE TRIGGER was added in MySQL 5.0.2. Currently, its use requires the SUPER privilege.

MySQL Enterprise.

For expert advice on creating triggers subscribe to the MySQL Enterprise Monitor. For more information see, http://www.mysql.com/products/enterprise/advisors.html.

The trigger becomes associated with the table named tbl_name, which must refer to a permanent table. You cannot associate a trigger with a TEMPORARY table or a view.

When the trigger is activated, the DEFINER clause determines the privileges that apply, as described later in this section.

trigger_time is the trigger action time. It can be BEFORE or AFTER to indicate that the trigger activates before or after the statement that activated it.

trigger_event indicates the kind of statement that activates the trigger. The trigger_event can be one of the following:

INSERT: The trigger is activated whenever a new row is inserted into the table; for example, through INSERT, LOAD DATA, and REPLACE statements.

UPDATE: The trigger is activated whenever a row is modified; for example, through UPDATE statements.

DELETE: The trigger is activated whenever a row is deleted from the table; for example, through DELETE and REPLACE statements. However, DROP TABLE and TRUNCATE statements on the table do not activate this trigger, because they do not use DELETE. See Section 11.2.9, “TRUNCATE Syntax”.

It is important to understand that the trigger_event does not represent a literal type of SQL statement that activates the trigger so much as it represents a type of table operation. For example, an INSERT trigger is activated by not only INSERT statements but also LOAD DATA statements because both statements insert rows into a table.

A potentially confusing example of this is the INSERT INTO ... ON DUPLICATE KEY UPDATE ... syntax: a BEFORE INSERT trigger will activate for every row, followed by either an AFTER INSERT trigger or both the BEFORE UPDATE and AFTER UPDATE triggers, depending on whether there was a duplicate key for the row.

There cannot be two triggers for a given table that have the same trigger action time and event. For example, you cannot have two BEFORE UPDATE triggers for a table. But you can have a BEFORE UPDATE and a BEFORE INSERT trigger, or a BEFORE UPDATE and an AFTER UPDATE trigger.

trigger_stmt is the statement to execute when the trigger activates. If you want to execute multiple statements, use the BEGIN ... END compound statement construct. This also enables you to use the same statements that are allowable within stored routines. See Section 17.2.5, “BEGIN ... END Compound Statement Syntax”. Some statements are not allowed in triggers; see Section F.1, “Restrictions on Stored Routines and Triggers”.

MySQL stores the sql_mode system variable setting that is in effect at the time a trigger is created, and always executes the trigger with this setting in force, regardless of the current server SQL mode.

Note

Currently, triggers are not activated by cascaded foreign key actions. This limitation will be lifted as soon as possible.

Note

Before MySQL 5.0.10, triggers cannot contain direct references to tables by name. Beginning with MySQL 5.0.10, you can write triggers such as the one named testref shown in this example:

CREATE TABLE test1(a1 INT);

CREATE TABLE test2(a2 INT);

CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);

CREATE TABLE test4(

a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

b4 INT DEFAULT 0

);

DELIMITER |

CREATE TRIGGER testref BEFORE INSERT ON test1

FOR EACH ROW BEGIN

INSERT INTO test2 SET a2 = NEW.a1;

DELETE FROM test3 WHERE a3 = NEW.a1;

UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;

END;

|

DELIMITER ;

INSERT INTO test3 (a3) VALUES

(NULL), (NULL), (NULL), (NULL), (NULL),

(NULL), (NULL), (NULL), (NULL), (NULL);

INSERT INTO test4 (a4) VALUES

(0), (0), (0), (0), (0), (0), (0), (0), (0), (0);

Suppose that you insert the following values into table test1 as shown here:

mysql> INSERT INTO test1 VALUES

-> (1), (3), (1), (7), (1), (8), (4), (4);

Query OK, 8 rows affected (0.01 sec)

Records: 8  Duplicates: 0  Warnings: 0

As a result, the data in the four tables will be as follows:

mysql> SELECT * FROM test1;

+------+

| a1   |

+------+

|    1 |

|    3 |

|    1 |

|    7 |

|    1 |

|    8 |

|    4 |

|    4 |

+------+

8 rows in set (0.00 sec)

mysql> SELECT * FROM test2;

+------+

| a2   |

+------+

|    1 |

|    3 |

|    1 |

|    7 |

|    1 |

|    8 |

|    4 |

|    4 |

+------+

8 rows in set (0.00 sec)

mysql> SELECT * FROM test3;

+----+

| a3 |

+----+

|  2 |

|  5 |

|  6 |

|  9 |

| 10 |

+----+

5 rows in set (0.00 sec)

mysql> SELECT * FROM test4;

+----+------+

| a4 | b4   |

+----+------+

|  1 |    3 |

|  2 |    0 |

|  3 |    1 |

|  4 |    2 |

|  5 |    0 |

|  6 |    0 |

|  7 |    1 |

|  8 |    1 |

|  9 |    0 |

| 10 |    0 |

+----+------+

10 rows in set (0.00 sec)

You can refer to columns in the subject table (the table associated with the trigger) by using the aliases OLD and NEW. OLD.col_name refers to a column of an existing row before it is updated or deleted. NEW.col_name refers to the column of a new row to be inserted or an existing row after it is updated.

The DEFINER clause specifies the MySQL account to be used when checking access privileges at trigger activation time. It was added in MySQL 5.0.17. If a user value is given, it should be a MySQL account in 'user_name'@'host_name' format (the same format used in the GRANT statement). The user_name and host_name values both are required. CURRENT_USER also can be given as CURRENT_USER(). The default DEFINER value is the user who executes the CREATE TRIGGER statement. (This is the same as DEFINER = CURRENT_USER.)

If you specify the DEFINER clause, you cannot set the value to any account but your own unless you have the SUPER privilege. These rules determine the legal DEFINER user values:

If you do not have the SUPER privilege, the only legal user value is your own account, either specified literally or by using CURRENT_USER. You cannot set the definer to some other account.

If you have the SUPER privilege, you can specify any syntactically legal account name. If the account does not actually exist, a warning is generated.

Although it is possible to create triggers with a non-existent DEFINER value, it is not a good idea for such triggers to be activated until the definer actually does exist. Otherwise, the behavior with respect to privilege checking is undefined.

Note: Because MySQL currently requires the SUPER privilege for the use of CREATE TRIGGER, only the second of the preceding rules applies. (MySQL 5.1.6 implements the TRIGGER privilege and requires that privilege for trigger creation, so at that point both rules come into play and SUPER is required only for specifying a DEFINER value other than your own account.)

From MySQL 5.0.17 on, MySQL checks trigger privileges like this:

At CREATE TRIGGER time, the user that issues the statement must have the SUPER privilege.

At trigger activation time, privileges are checked against the DEFINER user. This user must have these privileges:

The SUPER privilege.

The SELECT privilege for the subject table if references to table columns occur via OLD.col_name or NEW.col_name in the trigger definition.

The UPDATE privilege for the subject table if table columns are targets of SET NEW.col_name = value assignments in the trigger definition.

Whatever other privileges normally are required for the statements executed by the trigger.

Before MySQL 5.0.17, MySQL checks trigger privileges like this:

At CREATE TRIGGER time, the user that issues the statement must have the SUPER privilege.

At trigger activation time, privileges are checked against the user whose actions cause the trigger to be activated. This user must have whatever privileges normally are required for the statements executed by the trigger.

Note that the introduction of the DEFINER clause changes the meaning of CURRENT_USER() within trigger definitions: The CURRENT_USER() function evaluates to the trigger DEFINER value as of MySQL 5.0.17 and to the user whose actions caused the trigger to be activated before 5.0.17.

mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));

mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account

-> FOR EACH ROW SET @sum = @sum + NEW.amount;

mysql> SET @sum = 0;

mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-100.00);

mysql> SELECT @sum AS 'Total amount inserted';

+-----------------------+

| Total amount inserted |

+-----------------------+

| 1852.48               |

+-----------------------+

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

CREATE TABLE member (

id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,

name VARCHAR(32),

create_date TIMESTAMP DEFAULT '0000-00-00 00:00:00',

update_date TIMESTAMP DEFAULT '0000-00-00 00:00:00',

PRIMARY KEY (id)

);

DELIMITER //

CREATE TRIGGER member_before_insert

BEFORE INSERT ON member

FOR EACH ROW

BEGIN

SET NEW.create_date = NOW(), NEW.update_date = '0000-00-00 00:00:00';

END;//

CREATE TRIGGER member_before_update

BEFORE UPDATE ON member

FOR EACH ROW

BEGIN

SET NEW.update_date = NOW(), NEW.create_date = OLD.create_date;

END;//

DELIMITER ;

Testing Example 1.

> INSERT INTO member (name) VALUES ('newton'), ('albert'), ('witten');

> UPDATE member SET name='einstein' WHERE id=2;

> SELECT * FROM member;

+----+----------+---------------------+---------------------+

| id | name     | create_date         | update_date

+----+----------+---------------------+---------------------+

|  1 | newton   | 2006-06-12 04:16:05 | 0000-00-00 00:00:00 |

|  2 | einstein | 2006-06-12 04:16:05 | 2006-06-12 04:16:36 |

|  3 | witten   | 2006-06-12 04:16:05 | 0000-00-00 00:00:00 |

+----+----------+---------------------+---------------------+

CREATE TABLE member_audit_trail(

event_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,

id SMALLINT UNSIGNED DEFAULT NULL,

old_name VARCHAR(32) DEFAULT NULL,

action ENUM('insert', 'update', 'delete') NOT NULL,

name VARCHAR(32) DEFAULT NULL,

changed DATETIME DEFAULT NULL,

PRIMARY KEY (event_id)

);

DELIMITER //

CREATE TRIGGER member_after_update

AFTER UPDATE ON member

FOR EACH ROW

BEGIN

INSERT INTO member_audit_trail

SET action='update', id=OLD.id, old_name=OLD.name, name=NEW.name, changed=NOW();

END;//

CREATE TRIGGER member_after_insert

AFTER INSERT ON member

FOR EACH ROW

BEGIN

INSERT INTO member_audit_trail

SET action='insert', id = NEW.id, name = NEW.name, changed=NOW();

END;//

CREATE TRIGGER member_after_delete

AFTER DELETE ON member

FOR EACH ROW

BEGIN

INSERT INTO member_audit_trail

SET action='delete', id=OLD.id, old_name=OLD.name, changed=NOW();

END;//

DELIMITER ;

# The edits we made in Example 1 show up in the audit trail.

> SELECT * FROM member_audit_trail;

+----------+------+----------+--------+----------+---------------------+|

event_id | id   | old_name | action | name     | changed             |+----------+------+----------+--------+----------+---------------------+

|        1 |    1 | NULL     | insert | newton   | 2006-06-12 04:16:05 |

|        2 |    2 | NULL     | insert | albert   | 2006-06-12 04:16:05 |

|        3 |    3 | NULL     | insert | witten   | 2006-06-12 04:16:05 |

|        4 |    2 | albert   | update | einstein | 2006-06-12 04:16:36 |+----------+------+----------+--------+----------+--------------------

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mysql create triggers_mysql 触发器的创建 的相关文章

  • 距离大决战777天——目前的进度

    最近看上了两款开发板 一是大名鼎鼎的合宙C3 看上他是因为9 9的无敌性价比 二是某黄厂的st7789s3 看上他是因为始终的大小和性价比 有着一块170 320的屏 S3处理起来刚好得心应手 58元的价位也是蛮能打 秒杀其他大厂的板子的配
  • OpenMMLab实训16班--第一节

    OpenMMLab实训16班 第一节 主讲人 张子豪 主题 计算机视觉与Openmmlab入门 内容 一 计算视觉基础 计算机视觉任务主要分为分类 检测 分割三类任务 计算机视觉基础问题都是对图像进行模式识别和数据挖掘 二 openmmla
  • 魔方游戏(附游戏开源代码)

    这个魔方游戏的前期的实现参考了许多教程 但全部代码逻辑都是本人写的 借鉴了的都会给出原贴链接 只讲实现的思路 已完成 魔方的转动和魔方的动画效果 支持魔方的cfop全部公式 按按钮可转动魔方 按键盘上的alt键可用移动鼠标360无死角观察魔
  • 二维数组与字符数组部分实验

    学习目标 1 掌握与数组有关的算法 2 掌握二维数组的定义 存储结构 初始化及输入 输出的方法 3 掌握字符数组的定义 初始化及输入 输出的方法 4 掌握字符串和字符串函数的使用 学习内容 1 编写程序实现 输出二维数组 数值型 每一行的最
  • 轨迹路线相似度计算

    概述 在日常生活中很多场景应用到了轨迹相似度的计算 如 地图路线匹配 发现新冠病毒易感人群等 目前主要使 的相似性分析 法可以分为基于规整的方法 包括动态时间规整 DTW 最 公共 序列 LCSS 和基于真实序列的编辑距离 EDR 等 和基
  • 内推几何建模与图形渲染职位

    最近 可能也会是长期的 公司在大力招兵买马 急缺几何 图形方面的人才 初级 高级 专家或有致力于图形领域方面开发都欢迎 当然其他方面的也有 包括BIM相关的开发 可直接内推 具体职位列表如下 薪资open可谈 坐标 上海 深圳 武汉三地均可
  • android shape 的使用

    Android中常常使用shape来定义控件的一些显示属性它可以作为一般图片使用 今天看了一些shape的使用 对shape有了大体的了解 稍作总结 先看下面的代码 复制到剪贴板 XML HTML代码
  • @umijs/plugin-locale使用

    介绍 plugin locale是一个国际化的插件 用于解决i18n问题 约定式的多语言支持 可以进行多个国际语言的切换 启用方式 在umirc ts文件中配置locale 开启 使用 在src下创建一个locales文件夹 在文件夹下配置
  • python 简单使用MNIST数据集实现手写数字识别

    一 了解MNIST数据集 import tensorflow as tf import tensorflow examples tutorials mnist input data as input data import matplotl
  • @Service注解怎么使用?@Service注解的用法

    Service注解用于类上 标记当前类是一个service类 加上该注解会将当前类自动注入到spring容器中 不需要再在applicationContext xml文件定义bean了 自动扫描路径下面的包的时候 如果一个类带了 Servi
  • 绕过登录的万能密码 SQL 注入

    Portswigger练兵场之SQL注入 SQL 注入 绕过登录的万能密码 Lab SQL injection vulnerability allowing login bypass 实验前置必要知识点 正常一个没有防护的应用程序 允许用户
  • PCL 半径滤波(C++详细过程版)

    半径滤波 一 概述 二 代码实现 三 结果展示 1 原始点云 2 滤波结果 一 概述 半径滤波在PCL里有现成的调用函数 具体算法原理和实现代码见 PCL 半径滤波器 之所以要写算法详细实现过程是为了对算法进行改进 二 代码实现 inclu
  • java--基础--22--Lambda

    java 基础 22 Lambda 代码 https gitee com DanShenGuiZu learnDemo tree mysql mybaties DB jdk8 learn 1 组成Lambda表达式的三要素 形式参数 箭头
  • unity获取脚本组件_Unity小练习学C#之获取Animator组件并控制

    本人是C 初学者 可能有些说法不太合适 请各位多多指教 希望在你们的指导中快速成长 本次目标 能使用UI Button 控制角色的动画状态切换 Unity小练习学C 之获取Animatorhttps www zhihu com video
  • 什么是Linux系统

    一 什么是Linux系统 系统简介 Linux 全称GNU Linux 是一套免费使用和自由传播的类Unix操作系统 是一个基于POSIX的多用户 多任务 支持多线程和多CPU的操作系统 伴随着互联网的发展 Linux得到了来自全世界软件爱
  • 在服务器上搭建网站

    我们购买云服务器后 进入服务器windows界面 会有几个个重要的系统软件 其中有FileZillaServerInterface 和 Internet信息服务 ISS 管理器 FileZillaServerInterface 是用来与FT
  • Orangepi Zero2——系统启动及wiringPi外设SDK安装

    文章目录 平台介绍 刷机和系统启动 工具 登录 串口登录 修改登录密码 网络配置 串口登录下修改内核日志输出级别 SSH登录开发板 基于官方外设开发 wiringPi外设SDK安装 平台介绍 配置图 背面图 引脚功能图 特性 CPU 全志H
  • Matlab中的傅里叶级数展开函数

    今天在用Matlab 2012b 计算的时候发现其中的函数库没有直接提供傅里叶级数展开的函数 就自己搞了一个 function A B F fseries f x n a b 用于求解函数的傅里叶级数展开 if nargin 3 a pi
  • .ply模型格式解析与Loader编写

    格式介绍 PLY作为一种多边形模型数据格式 不同于三维引擎中常用的场景图文件格式和脚本文件 每个PLY文件只用于描述一个多边形模型对象Object 该模型对象可以通过诸如顶点 面等数据进行描述 被统称作元素Element PLY的文件结构是

随机推荐

  • Matlab:数模03-灰色预测

    文章目录 关于灰色预测模型 累加生成 GM 1 1 模型 GM 1 1 模型的精度检验 Matlab代码 数据测试 01 数据测试 02 用途 关于灰色预测模型 累加生成 在累加生成的基础上 我们建立了GM 1 1 模型 GM 1 1 模型
  • 极大似然估计和最大后验估计

    https baijiahao baidu com s id 1593811166204755239 wfr spider for pc 机器学习中 一般只得到业务产生的数据集D 机器学习目的是通过数据D了解该项业务的过去 建模 和未来 预
  • C#学习教程之三

    C 类是一种数据结构 它可以封装数据成员 函数成员和其他的类 类是创建对象的模版 C 的一切类型都是类 所有的语句都必须位于类内 不存在任何游离于类外的语句 因此 类是C 语言的核心和基本构成模块 C 类 类是从实际对象中抽象出来的一种完整
  • mybatis整合spring之mapperLocations和typeAliasesPackage(mapper-locations和type-aliases-package)

    Spring整合
  • reactnative textinput禁止弹出键盘_定了!这个考试禁止携带计算器!证券从业考试可以带吗?(附计算器使用汇总)...

    hi 大家好 我是大咖罗 都说考证是赶早不赶晚 考试政策的变化总是来得猝不及防 01 会计中级考试 禁止携带计算器 前不久 财政部紧急发布 关于修订印发 全国会计专业技术资格考试考场规则 等文件的通知 通知中明确 携带准考证和有效居民身份证
  • linux 时间通知链机制,linux内核的通知链机制

    一 为什么需要通知链 linux内核的各个子系统之间往往互相关联 一个子系统产生或者侦测到的事件 其它的子系统往往也很感兴趣 因此linux内核采用了通知链机制实现内核的子系统之间的通信需求 值的注意的是 通知链机制仅用于内核内部的子系统之
  • 三阶魔方自动还原 vc实现

    魔方自动求解程序一般有两种方法 一种是按照人还原魔方的步骤 一步步来 另外一种是使用数学方法 魔方自有一套复杂的数学理论 其中较著名的是两阶段算法 压缩文件中的cube430 exe使用的就是数学方法 程序作者便是two phase算法发明
  • BurpSuite超详细安装教程-功能概述-配置-使用教程---(附下载链接)

    一 介绍 BurpSuite是渗透测试 漏洞挖掘以及Web应用程序测试的最佳工具之一 是一款用于攻击web 应用程序的集成攻击测试平台 可以进行抓包 重放 爆破 包含许多工具 能处理对应的HTTP消息 持久性 认证 代理 日志 警报 二 工
  • 使用Cobra开发自己的命令行工具

    Cobra 项目地址 https github com spf13 cobra 1 新建cobra项目 安装cobra cli工具 go install github com spf13 cobra cli latest 新建项目目录 mk
  • 扫盲-----addEventlistener()方法,事件监听(一)

    一 扫盲事件起因 时间 2018年6月1日周五下午 原本我以为我已经把当前的bug改好 应该没啥问题了 坐等下班公司聚餐 开心 突然 隔壁同组大哥 哎 cp 你看看 你这个首页报了很多错哎 我的第一反应就是 不可能 怎么会有错误呢 我明明都
  • osgEarth的Rex引擎原理分析(七十二)如何从高程影像变成高程网格

    目标 七十一 中的问题143 有两种方法 1 对高程影像进行采样 用采样值来设置高程 通过CPU实现 2 通过着色器来实现 在GPU上进行操作 待继续分析列表 9 earth文件中都有哪些options 九 中问题 10 如何根据earth
  • jQuery甘特图/日程图/横道图/插件

    基于JQ的一款灵活高效 支持自定义拓展的甘特图 日程图插件 支持月 周 小时等显示方式 支持拖动改变时间 展开与收起 添加 删除 刷新 节假日高亮 clicked dblClicked changed事件 调用方式 ganttChart g
  • 【备战csp-j】 csp常考题型详解(1)

    一 计算机基础知识 1 微型计算机的问世是由于 的出现 A 中小规模集成电路 B 晶体管电路 C 超 大规模集成电路 D 电子管电路 答案 C 解析 年代 元件 第一代 1946 1958 电子管 第二代 1959 1964 晶体管 第三代
  • Vue使用three.js的GLTFLoader导入外部模型绘制边界

    一 效果展示 threeJs渲染外部模型视频 二 项目引用 将OrbitControls和GLTFLoader引入到项目中 import as THREE from three 引入three import OrbitControls fr
  • NYOJ 586 疯牛 & POJ 2456(二分搜索 + 贪心)

    疯牛 时间限制 1000 ms 内存限制 65535 KB 难度 4 描述 农夫 John 建造了一座很长的畜栏 它包括N 2 lt N lt 100 000 个隔间 这些小隔间依次编号为x1 xN 0 lt xi lt 1 000 000
  • 设计模式(十五)-面向对象概念

    软件设计 十五 UML建模 下 https blog csdn net ke1ying article details 129152487 一 设计原则 1 单一职责 设计目的单一的类 2 开放 封闭原则 对扩展开放 对修改关闭 3 里氏替
  • Elasticsearch集群内存占用高?用这招!

    一 freeze index冻结索引介绍 Elasticsearch为了能够实现高效快速搜索 在内存中维护了一些数据结构 当索引的数量越来越多 那么这些数据结构所占用的内存也会越来越大 这是一个不可忽视的损耗 在实际的业务开展过程中 我们会
  • 电容触摸式操作面板按键方案选型

    系列文章目录 1 元件基础 2 电路设计 3 PCB设计 4 元件焊接 5 板子调试 6 程序设计 7 算法学习 8 编写exe 9 检测标准 10 项目举例 11 职业规划 文章目录 前言 方案一 触摸弹簧 方案二 ITO导电玻璃 银浆触
  • Python爬虫库

    网络 通用 urllib 网络库 stdlib requests 网络库 grab 网络库 基于pycurl pycurl 网络库 绑定libcurl urllib3 Python HTTP库 安全连接池 支持文件post 可用性高 htt
  • mysql create triggers_mysql 触发器的创建

    CREATE TRIGGER Syntax CREATE DEFINER user CURRENT USER TRIGGER trigger name trigger time trigger event ON tbl name FOR E