欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

【mysql】mysql触发器before与after的区别

时间:2023-05-02

1.商品表

-- 创建商品表DROp TABLE IF EXISTS `goods`;CREATE TABLE `goods` ( `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '商品id', `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '商品名称', `num` int(0) DEFAULT NULL COMMENT '数量', PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of goods-- ----------------------------INSERT INTO `goods` VALUES (1, '辣条', -10);INSERT INTO `goods` VALUES (2, '棒棒糖', 10);INSERT INTO `goods` VALUES (3, '酸奶', 10);

2.订单表

-- 创建订单表DROP TABLE IF EXISTS `order`;CREATE TABLE `order` ( `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '订单id', `goods_id` int(0) DEFAULT NULL COMMENT '商品id', `num` int(0) DEFAULT NULL COMMENT '商品数量', PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of order-- ----------------------------INSERT INTO `order` VALUES (1, 1, 20);

3.触发器

-- 创建触发器trigger1drop trigger if exists trigger1;DELIMITER $$create trigger trigger1 after insert on `order` for each row begin update goods set num=num-new.num where id = new.goods_id;end $$

//查看结果select * from `order`;insert into `order`(goods_id,num) values(1,20);select * from `goods`;

//创建触发器drop trigger if exists trigger2;DELIMITER $$create trigger trigger2 before insert on `order` for each row begin if new.num > 10 then set new.num = 10; end if; update goods set num=num-new.num where id = new.goods_id;end $$

//查看结果select * from `order`;insert into `order`(goods_id,num) values(1,20);select * from `goods`;

//mysql触发器中的before和after的区别:before:(insert、update)可以对new进行修改,after:不能对new进行修改,两者都不能修改old数据。insert语句只有new是合法的,新增的数据没有olddelete语句只有old是合法的,删除的数据没有newupdate语句new、old可以同时使用,有old new 两份after是先完成数据的增删改,再触发,触发的语句晚于监视的增删改操作,无法影响前面的增删改动作;也就是说先插入订单记录,再更新商品的数量;before是先完成触发,再增删改,触发的语句先于监视的增删改,这样就可以对new进行修改

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。