Mysql学习MySQL中触发器的基础学习教程

Mysql学习MySQL中触发器的基础学习教程,第1张

概述介绍《Mysql学习MySQL中触发器基础学习教程》开发教程,希望对您有用。

《MysqL学习MysqL中触发器的基础学习教程》要点:
本文介绍了MysqL学习MysqL中触发器的基础学习教程,希望对您有用。如果有疑问,可以联系我们。

0.触发器的基本概念
触发器是一种特殊的存储过程,它在插入,删除或修改特定表中的数据时触发执行,它比数据库本身标准的功能有更精细和更复杂的数据控制能力.MysqL学习

数据库触发器有以下的作用:MysqL学习

(1).安全性.可以基于数据库的值使用户具有 *** 作数据库的某种权利.MysqL学习

  # 可以基于时间限制用户的 *** 作,例如不允许下班后和节假日修改数据库数据.MysqL学习

  # 可以基于数据库中的数据限制用户的 *** 作,例如不允许股票的价格的升幅一次超过10%.MysqL学习

(2).审计.可以跟踪用户对数据库的 *** 作.  MysqL学习

  # 审计用户 *** 作数据库的语句.MysqL学习

  # 把用户对数据库的更新写入审计表.MysqL学习

(3).实现复杂的数据完整性规则MysqL学习

  # 实现非标准的数据完整性检查和约束.触发器可产生比规则更为复杂的限制.与规则不同,触发器可以引用列或数据库对象.例如,触发器可回退任何企图吃进超过自己保证金的期货.MysqL学习


  # 提供可变的缺省值.MysqL学习

(4).实现复杂的非标准的数据库相关完整性规则.触发器可以对数据库中相关的表进行连环更新.例如,在auths表author_code列上的删除触发器可导致相应删除在其它表中的与之匹配的行.MysqL学习

  # 在修改或删除时级联修改或删除其它表中的与之匹配的行.MysqL学习

  # 在修改或删除时把其它表中的与之匹配的行设成NulL值.MysqL学习

  # 在修改或删除时把其它表中的与之匹配的行级联设成缺省值.MysqL学习

  # 触发器能够拒绝或回退那些破坏相关完整性的变化,取消试图进行数据更新的事务.当插入一个与其主健不匹配的外部键时,这种触发器会起作用.例如,可以在books.author_code 列上生成一个插入触发器,如果新值与auths.author_code列中的某值不匹配时,插入被回退.MysqL学习

(5).同步实时地复制表中的数据.MysqL学习

(6).自动计算数据值,如果数据的值达到了一定的要求,则进行特定的处理.例如,如果公司的帐号上的资金低于5万元则立即给财务人员发送警告数据.MysqL学习


1. 创建触发器语法MysqL学习

CREATE [defineR = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_bodytrigger_time: { BEFORE | AFTER }trigger_event: { INSERT | UPDATE | DELETE }CREATE [defineR = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body trigger_time: { BEFORE | AFTER }trigger_event: { INSERT | UPDATE | DELETE }

语法相关部分说明:
1.1 授权与回收
创建触发器需要有CREATE TRIGGER权限:MysqL学习

grant create trigger on `database_naem`.`table_name` to `user_name`@`ip_address`;grant create trigger on `database_naem`.`table_name` to `user_name`@`ip_address`;

权限收回:MysqL学习

revoke create trigger on `database_naem`.`table_name` from `user_name`@`ip_address`;revoke create trigger on `database_naem`.`table_name` from `user_name`@`ip_address`;

1.2 trigger_name
必须给触发器命令,最多64个字符,建议用表的名字_触发器类型的缩写方法命名.如ttlsa_posts_bi(表ttlsa_posts,触发器发生在insert之前before)
1.3 defineR子句
在激活触发器时,检查访问权限,确保触发器安全使用.
1.4 trigger_time
定义触发器触发时间.可以设置为在行记录更改之前或之后发生.
1.5 trigger_event
定义触发器触发事件.触发的事件有:
1.5.1
INSERT:当一个新行插入到表中时触发.如INSERT、LOAD DATA和REPLACE语句.
UPDATE:当一个行数据被更改时触发.如UPDATE语句.
DELETE:当一个行从表中删除时触发.如DELETE和REPLACE语句. 注意:DROP table和TruncATE table语句不会触发该触发器,因为它们不是使用DELETE.同样删除一个分区表也不会触发.
有一个潜在的混乱情况,如INSERT INTO ... ON DUPliCATE KEY UPDATE ... 取决于是否有重复键行.
不能对一个表创建具有相同的触发事件和触发时间的多个触发器.如对于一个表不能创建两个BEFORE UPDATE触发器,但是,可以创建一个BEFORE UPDATE和一个BEFORE INSERT或一个BEFORE UPDATE和一个AFTER UPDATE触发器.
1.6 FOR EACH ROW子句
定义触发执行间隔.FOR EACH ROW子句定义触发器每隔一行执行一次动作,而不是对整个表执行一次.
1.7 trigger_body子句
包含要触发执行的SQL语句.可以是任何合法的语句,包括复合语句(需要使用BEGIN ... END结构),流控制语句(if、case、while、loop、for、repeat、leave、iterate),变量声明(declare)以及指派(set),异常处理声明,允许条件声明,但是这里的语句受的限制和函数的一样.
1.7.1 olD与NEW
在触发器的SQL语句中,可以关联表中的任何列,通过使用olD和NEW列名来标识,如olD.col_name、NEW.col_name.olD.col_name关联现有的行的一列在被更新或删除前的值.NEW.col_name关联一个新行的插入或更新现有的行的一列的值.
对于INSERT语句,只有NEW是合法的.否则会报错:ERROR 1363 (HY000): There is no olD row in on INSERT trigger
对于DELETE语句,只有olD是合法的.否则会报错:ERROR 1363 (HY000): There is no NEW row in on DELETE trigger
对于UPDATE语句,NEW和olD可以同时使用.
2. 实例
2.1 创建表
使用在《MysqLudf_Json将关系数据以JsON编码》一文中创建的表.后续会将用户表迁移到nosql数据库上的.MysqL学习

MysqL> create table `ttlsa_users` (  -> `uID` int(11) unsigned,-> `username` varchar(40) NOT NulL,-> `password` varchar(40) NOT NulL,-> `createtime` timestamp NOT NulL DEFAulT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,-> PRIMARY KEY (`uID`)  -> );MysqL> create table `ttlsa_users` (  -> `uID` int(11) unsigned,-> PRIMARY KEY (`uID`)  -> );

创建另外一张表来存放触发器动作数据.MysqL学习

MysqL> create table `ttlsa_users3` (  -> `uID` int(11) unsigned,-> `userinfo` varchar(200),-> );MysqL> create table `ttlsa_users3` (  -> `uID` int(11) unsigned,-> );

2.2 创建触发器MysqL学习

MysqL> delimiter //MysqL> create trigger ttlsa_users_ai  -> after insert on ttlsa_users  -> for each row  -> insert into ttlsa_users3 (uID,userinfo) values(uID,Json_object(NEW.uID,NEW.username,NEW.password));  -> //MysqL> create trigger ttlsa_users_au  -> after update on ttlsa_users  -> for each row  -> update ttlsa_users3 set userinfo=Json_object(NEW.uID,NEW.password) where uID=olD.uID;  -> //MysqL> delimiter //MysqL> create trigger ttlsa_users_ai  -> after insert on ttlsa_users  -> for each row  -> insert into ttlsa_users3 (uID,NEW.password));  -> // MysqL> create trigger ttlsa_users_au  -> after update on ttlsa_users  -> for each row  -> update ttlsa_users3 set userinfo=Json_object(NEW.uID,NEW.password) where uID=olD.uID;  -> //

2.3 测试MysqL学习

MysqL> insert into ttlsa_users values (890,'xuhh',md5('abc'),NulL,'test trigger')//
query OK,1 row affected (0.01 sec)
MysqL> select * from ttlsa_users//
+-----+-------------+----------------------------------+---------------------+------------------------------------+| uID | username  | password             | createtime     | Json_data             |+-----+-------------+----------------------------------+---------------------+------------------------------------+| 888 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 11:27:01 | \website\ - "http://www.ttlsa.com" || 889 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 14:08:44 | xuhh                || 890 | xuhh    | 900150983cd24fb0d6963f7d28e17f72 | 2013-08-14 16:40:49 | test trigger            |+-----+-------------+----------------------------------+---------------------+------------------------------------+3 rows in set (0.00 sec)
MysqL> select * from ttlsa_users3//
+-----------------------------------------------------------------------------+------+| userinfo                                  | uID |+-----------------------------------------------------------------------------+------+| {"uID":890,"username":"xuhh","password":"900150983cd24fb0d6963f7d28e17f72"} | 890 |+-----------------------------------------------------------------------------+------+2 rows in set (0.00 sec)
MysqL> update ttlsa_users set password='test_update' where uID=890//
query OK,1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0
MysqL> select * from ttlsa_users//
+-----+-------------+----------------------------------+---------------------+------------------------------------+| uID | username  | password             | createtime     | Json_data             |+-----+-------------+----------------------------------+---------------------+------------------------------------+| 888 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 11:27:01 | \website\ - "http://www.ttlsa.com" || 889 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 14:08:44 | xuhh                || 890 | xuhh    | test_update           | 2013-08-14 16:41:33 | test trigger            |+-----+-------------+----------------------------------+---------------------+------------------------------------+3 rows in set (0.00 sec)
MysqL> select * from ttlsa_users3//
+-----------------------------------------------------------------------------+------+| userinfo                                  | uID |+-----------------------------------------------------------------------------+------+| {"uID":890,"password":"test_update"}           | 890 |+-----------------------------------------------------------------------------+------+2 rows in set (0.00 sec)
MysqL> insert into ttlsa_users values (890,1 row affected (0.01 sec)

 
MysqL学习

MysqL> select * from ttlsa_users//
+-----+-------------+----------------------------------+---------------------+------------------------------------+| uID | username  | password             | createtime     | Json_data             |+-----+-------------+----------------------------------+---------------------+------------------------------------+| 888 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 11:27:01 | \website\ - "http://www.ttlsa.com" || 889 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 14:08:44 | xuhh                || 890 | xuhh    | 900150983cd24fb0d6963f7d28e17f72 | 2013-08-14 16:40:49 | test trigger            |+-----+-------------+----------------------------------+---------------------+------------------------------------+3 rows in set (0.00 sec)

 
MysqL学习

MysqL> select * from ttlsa_users3//
+-----------------------------------------------------------------------------+------+| userinfo                                  | uID |+-----------------------------------------------------------------------------+------+| {"uID":890,"password":"900150983cd24fb0d6963f7d28e17f72"} | 890 |+-----------------------------------------------------------------------------+------+2 rows in set (0.00 sec) 
MysqL> update ttlsa_users set password='test_update' where uID=890//
query OK,1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0

 
MysqL学习

MysqL> select * from ttlsa_users//
+-----+-------------+----------------------------------+---------------------+------------------------------------+| uID | username  | password             | createtime     | Json_data             |+-----+-------------+----------------------------------+---------------------+------------------------------------+| 888 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 11:27:01 | \website\ - "http://www.ttlsa.com" || 889 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 14:08:44 | xuhh                || 890 | xuhh    | test_update           | 2013-08-14 16:41:33 | test trigger            |+-----+-------------+----------------------------------+---------------------+------------------------------------+3 rows in set (0.00 sec)

 
MysqL学习

MysqL> select * from ttlsa_users3//
+-----------------------------------------------------------------------------+------+| userinfo                                  | uID |+-----------------------------------------------------------------------------+------+| {"uID":890,"password":"test_update"}           | 890 |+-----------------------------------------------------------------------------+------+2 rows in set (0.00 sec)

3. 管理
3.1 列出触发器MysqL学习

MysqL> SHOW TRIGGERS like '%ttlsa%'; 触发器名称匹配%ttlsa%
*************************** 1. row ***************************       Trigger: ttlsa_users_ai        Event: INSERT        table: ttlsa_users      Statement: insert into ttlsa_users3 (uID,userinfo) values(NEW.uID,NEW.password))       Timing: AFTER       Created: NulL      sql_mode: NO_ENGINE_SUBSTITUTION       definer: root@127.0.0.1character_set_clIEnt: utf8collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci*************************** 2. row ***************************       Trigger: ttlsa_users_au        Event: UPDATE        table: ttlsa_users      Statement: update ttlsa_users3 set userinfo=Json_object(NEW.uID,NEW.password) where uID=olD.uID       Timing: AFTER       Created: NulL      sql_mode: NO_ENGINE_SUBSTITUTION       definer: root@127.0.0.1character_set_clIEnt: utf8collation_connection: utf8_general_ci Database Collation: latin1_swedish_ci2 rows in set (0.00 sec)
MysqL> SHOW TRIGGERS; #列出所有MysqL> SHOW TRIGGERS from database_name; #列出数据库的触发器MysqL> SHOW CREATE TRIGGER trigger_name;  #查看创建触发器
*************************** 1. row ***************************        Trigger: ttlsa_users_ai       sql_mode: NO_ENGINE_SUBSTITUTIONsql Original Statement: CREATE defineR=`root`@`127.0.0.1` trigger ttlsa_users_ai after insert on ttlsa_users for each row insert into ttlsa_users3 (uID,NEW.password)) character_set_clIEnt: utf8 collation_connection: utf8_general_ci  Database Collation: latin1_swedish_ci1 row in set (0.01 sec)

3.2 informatION_SCHEMA.TRIGGERS表MysqL学习

sql> SHOW TRIGGERS like '%ttlsa%'; #触发器名称匹配%ttlsa%
*************************** 1. row ***************************       Trigger: ttlsa_users_ai        Event: INSERT        table: ttlsa_users      Statement: insert into ttlsa_users3 (uID,NEW.password)) character_set_clIEnt: utf8 collation_connection: utf8_general_ci  Database Collation: latin1_swedish_ci1 row in set (0.01 sec)
MysqL> SELECT * FROM informatION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA='test' AND TRIGGER_name='ttlsa_users_au'\G
*************************** 1. row ***************************      TRIGGER_CATALOG: def      TRIGGER_SCHEMA: test       TRIGGER_name: ttlsa_users_au    EVENT_MANIPulATION: UPDATE   EVENT_OBJECT_CATALOG: def    EVENT_OBJECT_SCHEMA: test    EVENT_OBJECT_table: ttlsa_users       ACTION_ORDER: 0     ACTION_CONDITION: NulL     ACTION_STATEMENT: update ttlsa_users3 set userinfo=Json_object(NEW.uID,NEW.password) where uID=olD.uID    ACTION_ORIENTATION: ROW       ACTION_TIMING: AFTERACTION_REFERENCE_olD_table: NulLACTION_REFERENCE_NEW_table: NulL ACTION_REFERENCE_olD_ROW: olD ACTION_REFERENCE_NEW_ROW: NEW          CREATED: NulL         sql_mode: NO_ENGINE_SUBSTITUTION          defineR: root@127.0.0.1   CHaraCTER_SET_CLIENT: utf8   ColLATION_CONNECTION: utf8_general_ci    DATABASE_ColLATION: latin1_swedish_ci1 row in set (0.00 sec)
MysqL> SELECT * FROM informatION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA='test' AND TRIGGER_name='ttlsa_users_au'\G
*************************** 1. row ***************************      TRIGGER_CATALOG: def      TRIGGER_SCHEMA: test       TRIGGER_name: ttlsa_users_au    EVENT_MANIPulATION: UPDATE   EVENT_OBJECT_CATALOG: def    EVENT_OBJECT_SCHEMA: test    EVENT_OBJECT_table: ttlsa_users       ACTION_ORDER: 0     ACTION_CONDITION: NulL     ACTION_STATEMENT: update ttlsa_users3 set userinfo=Json_object(NEW.uID,NEW.password) where uID=olD.uID    ACTION_ORIENTATION: ROW       ACTION_TIMING: AFTERACTION_REFERENCE_olD_table: NulLACTION_REFERENCE_NEW_table: NulL ACTION_REFERENCE_olD_ROW: olD ACTION_REFERENCE_NEW_ROW: NEW          CREATED: NulL         sql_mode: NO_ENGINE_SUBSTITUTION          defineR: root@127.0.0.1   CHaraCTER_SET_CLIENT: utf8   ColLATION_CONNECTION: utf8_general_ci    DATABASE_ColLATION: latin1_swedish_ci1 row in set (0.00 sec)

3.3 删除触发器MysqL学习

MysqL> drop trigger trigger_name;MysqL> drop trigger trigger_name;

 MysqL学习

总结

以上是内存溢出为你收集整理的Mysql学习MySQL中触发器的基础学习教程全部内容,希望文章能够帮你解决Mysql学习MySQL中触发器的基础学习教程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/1159933.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存