#1.创建user用户表
CREATE TABLE `user` (`id` int(11) NOT NULL auto_increment COMMENT '用户ID',
`name` varchar(50) NOT NULL default '' COMMENT '名称',
`sex` int(1) NOT NULL default '0' COMMENT '0为男,1为女',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
INSERT INTO `user` (`id`, `name`, `sex`) VALUES
(1, '张映', 0),
(2, 'tank', 0);
#2.创建comment评论表
CREATE TABLE `comment` (
`c_id` int(11) NOT NULL auto_increment COMMENT '评论ID',
`u_id` int(11) NOT NULL COMMENT '用户ID',
`name` varchar(50) NOT NULL default '' COMMENT '用户名称',
`content` varchar(1000) NOT NULL default '' COMMENT '评论内容',
PRIMARY KEY (`c_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
INSERT INTO `comment` (`c_id`, `u_id`, `name`, `content`) VALUES
(1, 1, '张映', '触发器测试'),
(2, 1, '张映', '解决字段冗余'),
(3, 2, 'tank', '使代码更简单');
#3.更新name触发器
delimiter || #//mysql 默认结束符号是分号,当你在写触发器或者存储过程时有分号出现,会中止转而执行drop trigger if exists updatename|| #//删除同名的触发器,
create trigger updatename after update on user for each row #//建立触发器,
begin
#//old,new都是代表当前操作的记录行,你把它当成表名,也行;
if new.name!=old.name then #//当表中用户名称发生变化时,执行
update comment set comment.name=new.name where comment.u_id=old.id;
end if;
end||
delimiter ;
#4,触发器删除comment数据
delimiter ||
drop trigger if exists deletecomment||
create trigger deletecomment before delete on user for each row
begin
delete from comment where comment.u_id=old.id;
end||
delimiter ;
#5.测试触发器
#a,测试updata触发器
update user set name='苍鹰' where id = 1;
#b,测试delete触发器
delete from user where id = 1;
#显示所有的触发器
show triggers;
#删除触发器
drop trigger if exists updatename;
drop trigger if exists deletecomment;
#删除表
drop table if exists user;
drop table if exists comment;
转载:http://www.jb51.net/article/49207.htm