今天用到mysql的触发器,需要将被触发的行的数据沉淀到另一张表中,网上查了下资料,在此做个汇总,触发器的基本知识请参考:http://zhangjq5.iteye.com/admin/blogs/1893926
触发器建立在表的行上面,相当于对每行做监听,主要负责监听insert、delete和update操作,以update为例,
1、创建源数据表:
CREATE TABLE IF NOT EXISTS `test_trigger` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`insert_name` varchar(50) DEFAULT NULL,
`insert_desc` varchar(50) DEFAULT NULL,
`create_time` date DEFAULT NULL,
`time_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='触发器测试';
2、创建目标数据表:
CREATE TABLE IF NOT EXISTS `test_update` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`create_time` date DEFAULT NULL,
`time_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='更新test_trigger后,将数据同步到当前表';
3、触发器:
AFTER update ON test_trigger