一、建表并插入数据
mysql> create table goods(
-> gid char(8) primary key,
-> name varchar(10),
-> price decimal(8,2),
-> num int );
mysql> create table orders(
-> oid int primary key auto_increment,
-> gid char(10) not null,
-> name varchar(10),
-> price decimal(8,2),
-> onum int,
-> otime date );
mysql> insert into goods values
-> ('A0001','橡皮',2.5,100),
-> ('B0001','小楷本',2.8,210),
-> ('C0001','铅笔',1.2,120),
-> ('D0001','计算器',28,20);
二、触发器
1.建立触发器,订单表中增加订单数量后,商品表商品数量同步减少对应的商品订单出数量,并测试
mysql> create trigger orders_after_insert_trigger after insert on orders for each row
-> update goods set num=num-new.onum
-> where gid=goods.gid;
测试
#插入订单
mysql> insert into orders(gid,name,price,onum,otime) values('A001','橡皮',2.5,20,now());
查看编号A0001的商品库存num由100变为80
2.建立触发器,实现功能:客户取消订单,恢复商品表对应商品的数量
mysql> create trigger orders_after_delete_trigger after delete on orders for each row
-> update goods set num=num+old.onum
-> where gid=goods.gid;
测试
delete from orders where gid='A0001';
删除订单后,编号A0001的商品库存num由80变为原来的100
3.建立触发器,实现功能:客户修改订单,商品表对应商品数量同步更新
mysql> create trigger orders_after_update_trigger after update on orders foreach row
-> update goods set num=num+(old.onum-new.onum)
-> where gid=goods.gid;
测试
mysql-> insert into orders(gid,name,price,onum,otime) values('A0001','橡皮',2.5,20,now());
mysql> update orders set onum=35;
将订单量由20变为35,商品库存同时修改为65
三、存储过程
1.使用mydb7_openlab库
mysql> use mydb7_openlab
展示表
2.创建提取emp_new表所有员工姓名和工资的存储过程s1
mysql> delimiter //
mysql> create procedure s1()
-> begin
-> select name,incoming from emp_new;
-> end//
mysql> delimiter ;
mysql> call s1(); #调用s1()
3.创建存储过程s2,实现输入员工姓名后返回员工的年龄
mysql> delimiter //
mysql> create procedure s2(in in_name varchar(11),out out_age int)
-> begin
-> select age into out_age from emp_new where name=in_name;
-> end//
mysql> delimiter ;
测试:输入员工姓名“王五”
mysql> call s2('王五',@out_age);
mysql> select @out_age;
4.创建一个存储过程s3,有2个参数,传入部门号,返回该部门的平均工资
mysql> delimiter //
mysql> create procedure s3(in in_dept int,out out_avg_sal double)
-> begin
-> select round(avg(incoming),2) into out_avg_sal from emp_new where dept2=in_dept;
-> end//
mysql> delimiter ;
测试:输入部门号101
mysql> call s3(101,@avg_sal);
mysql> select @avg_sal;