1. 程式人生 > 資料庫 >MySQL複習

MySQL複習

create table goods(   #商品表
gid char(10),  #商品編號
number int   #庫存數目
);

create table order_detail(   #訂單表
gid char(10),
number int,  #下單數目
ordertime timestamp
);
insert into goods values("P1",100),("P2",100);
insert into order_detail values("P1",100,"2020-01-20 12:33:33"),("P2",100,"2020-01-20 12:33:33");

1.建立一個觸發器,當訂貨時,會判斷庫存是否夠,如果夠,則訂貨資訊會順利的寫入order_detail表,

庫存資訊更新,如果該商品庫存不夠,報錯"商品庫存不足"

create trigger p_i_order_detail before insert on order_detail for each ROW
BEGIN
declare f int;
select number into f from goods where gid=new.gid;
if f>new.number then update goods set number=number-new.number where gid=new.gid;
else SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "庫存不足",MYSQL_ERRNO = 1333; 
end if;
end;

2.建立一個觸發器,如果商品表商品編號變了,訂單表商品編號隨之改變

create TRIGGER p_change AFTER UPDATE on goods for each ROW
begin
	if new.gid != old.gid then
		update order_detail set gid = new.gid where gid = old.gid;
	end if;
end;

寫出2後,測試下訂單(往order_detail表中插入資料):gid=“p1”,number=10 ,能成功嗎?如果能,舉手,如果不能,找到原因修改

select * from goods;
insert into order_detail values("p1",10,"2020-01-20 12:33:33");


drop trigger p_change;