mysql学习之触发器
在借阅表和读者表当中存在着这样的关系,如果在借阅表当中添加一条数据,读者表当中对应的累计借书字段就自增1,如果在借阅表当中删除一条数据,读者表当中对应的累计借书字段就自减1,实现本功能的方法如下。
1、创建读者表
1 CREATE TABLE `t_borrowbook` ( 2 `borrowBookId` int(11) NOT NULL AUTO_INCREMENT, 3 `bookId` int(11) DEFAULT NULL, 4 `id` int(11) DEFAULT NULL, 5 `audienceId` int(11) DEFAULT NULL, 6 `startTime` datetime DEFAULT NULL, 7 `endTime` datetime DEFAULT NULL, 8 `borrowBookDesc` text, 9 PRIMARY KEY (`borrowBookId`) 10 )
2、创建借阅表
1 CREATE TABLE `t_audience` ( 2 `audienceId` int(10) NOT NULL AUTO_INCREMENT, 3 `audienceName` varchar(20) NOT NULL, 4 `audienceTypeId` int(10) NOT NULL, 5 `audienceNumber` varchar(18) NOT NULL, 6 `sex` varchar(20) DEFAULT NULL, 7 `cellphone` varchar(11) DEFAULT NULL, 8 `borrowBookNum` int(10) DEFAULT NULL, 9 `audienceDesc` text, 10 PRIMARY KEY (`audienceId`) 11 )
3、创建插入自增触发器
1 DELIMITER $$ 2 3 CREATE 4 /*[DEFINER = { user | CURRENT_USER }]*/ 5 TRIGGER `db_book`.`Tr_borrowbook_Insert` AFTER INSERT 6 ON `db_book`.`t_borrowbook` 7 FOR EACH ROW BEGIN 8 UPDATE t_audience SET borrowBookNum = borrowBookNum+1 WHERE audienceId=new.audienceId; 9 END$$ 10 11 DELIMITER ;
4、创建删除自减触发器
1 DELIMITER $$ 2 3 CREATE 4 /*[DEFINER = { user | CURRENT_USER }]*/ 5 TRIGGER `db_book`.`Tr_borrowbook_Delete` AFTER DELETE 6 ON `db_book`.`t_borrowbook` 7 FOR EACH ROW BEGIN 8 UPDATE t_audience SET borrowBookNum = borrowBookNum-1 WHERE audienceId=old.audienceId; 9 END$$ 10 11 DELIMITER ;
每天进步一点点,一切都是最好的安排。