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.触发器
-- 创建触发器trigger1
drop 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是合法的,新增的数据没有old
delete语句只有old是合法的,删除的数据没有new
update语句new、old可以同时使用,有old new 两份
after是先完成数据的增删改,再触发,触发的语句晚于监视的增删改操作,无法影响前面的增删改动作;也就是说先插入订单记录,再更新商品的数量;
before是先完成触发,再增删改,触发的语句先于监视的增删改,这样就可以对new进行修改
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92372.html