(1) 创建一个表alvin
create table alvin(
useridint(10),
usernamevarchar(20),
oldint(4),
address varchar(30));
(2) 创建一个表为trigger_time 用来存放触发后条件的结果
create table trigger_time(
zhixing_time time);
Query OK, 0 rows affected (0.15 sec)
(3)、创建只有单个执行语句的触发器
create trigger alvin1 before insert
on alvin for each row
insert into trigger_time values(now());
Query OK, 0 rows affected (0.07 sec)
(4)、创建有多个执行语句的触发器
举例一、
root@zytest 10:49>delimiter &&#告诉MYSQL该命令段下面的内容在提示结束后再执行分析。默认是以分号(;)执行
root@zytest 10:53>create trigger alvin3 after delete
->on alvin for each row
->begin
->insert into trigger_time values('21:01:01');
->insert into trigger_time values('22:01:01');
->end
->&&
Query OK, 0 rows affected (0.05 sec)
root@zytest 10:54>delimiter; #结束退出,注意分号要有空格
root@zytest 10:57>select * from alvin;
+--------+-------------+------+----------+
| userid | username| old| address|
+--------+-------------+------+----------+
|110 | zengxiaohua |28 | tianxing |
+--------+-------------+------+----------+
1 row in set (0.00 sec)
root@zytest 11:07>delete from alvin where userid='110';#执行删除动作看看触发器是否成功
Query OK, 1 row affected (0.05 sec)
root@zytest 11:07>select * from trigger_time;#:查看触发器的执行结果
+--------------+
| zhixing_time |
+--------------+
| 19:09:41|
| 21:01:01 |
| 22:01:01 |
+--------------+
3 rows in set (0.00 sec)
举例二、
alvin1表存放了学生的信息。每次增加(insert)一个学生的信息。就触发一次统计。统计结果存入aac表里面;
首先创建一个alvin1表结构
create table alvin1(
user_id int(10),
username varchar(20),
old tinyint(4),
address varchar(30));
create table aac(
my_count int);
然后开始创建一个触发器
delimiter &&
create trigger alvin123 before insert on
alvin1 for each row begin
declare ycount int(10);#:申明变量类型
set ycount=(select count(*) from alvin1);#:给变量赋值
insert into aac(my_count) values(ycount);#:调用变量
end &&
delimiter ;
root@zytest 16:24>insert into alvin1 values('1001','zhangsan','18','China');开始测试
root@zytest 16:24>select * from aac;查看触发器统计的结果。
(1) 查看所有触发器,提前要进入某库
#: show triggers \G;
(1)在triggers表中查看触发信息
(2)root@zytest 11:20>use information_schema;
root@zytest 11:19>select * from information_schema.triggers \G;
小技巧:所有触发器的信息都存在information_schema库中的triggers表里面,
在使用select 查询单个触发器的时候。可以根据triggers表里面的字段名称
Trigger_name字段进行查询。
root@information_schema 11:24>select * from triggers where trigger_name='alvin1'\G;
语法:
(1)、删除alvin1触发器
root@(none) 12:18>use zytest;
Database changed
root@zytest 12:18>drop trigger alvin1;
Query OK, 0 rows affected (0.03 sec)