什麼是觸發器?
觸發器是數據庫的一個程序,他是用來監聽著數據表的某個行為,一旦數據表的這個行為發生了,馬上執行相應的sql語句
觸發器的語法結構:
create trigger 觸發器的名稱觸發器事件 on 監聽的表名 for each row 行為發生後執行的sql語句
觸發器事件組成:;兩部分組成:
觸發器事件發生的時間-----是在監聽的表的行為 after before 常用的是after
觸發器執行的內容:增刪改
創建order 表的時候,需要注意,因為order在mysql中是一個關鍵字排序,為了避免錯誤的發生,我們可以添加反引號,表明這不是一個關鍵字
案例研究:
一旦生成訂單,對應的庫存表要減去相應的數據
(1)建兩張表 :一個商品goods表 一個訂單order表
mysql> create table goods(goods_id int primary key auto_increment,goods_name var
char(64),shop_price decimal(10,2),goods_number int)engine=mysiam default charset
=utf8;
mysql> create table `order`(goods_id int primary key auto_increment,goods_name v
archar(64),buy_number int)engine=mysiam default charset=utf8;
mysql> insert into goods values(null,'nokiaN85',2000,35),(null,'iphone4S',4500,3
0),(null,'Lnmia',5000,40),(null,'samsung',4200,20);
mysql> select*from goods;
+----------+------------+------------+--------------+
| goods_id | goods_name | shop_price | goods_number |
+----------+------------+------------+--------------+
| 1 | nokiaN85 | 2000.00 | 35 |
| 2 | iphone4S | 4500.00 | 30 |
| 3 | Lnmia | 5000.00 | 40 |
| 4 | samsung | 4200.00 | 20 |
+----------+------------+------------+--------------+
(2)創建觸發器
mysql> create trigger alter_goods_number after insert on `order` for each row up
date goods set goods_number=goods_number-5 where goods_id=1;
mysql> insert into `order` values(1,'nokiaN85',5);
mysql> select*from goods;
+----------+------------+------------+--------------+
| goods_id | goods_name | shop_price | goods_number |
+----------+------------+------------+--------------+
| 1 | nokiaN85 | 2000.00 | 30 |
| 2 | iphone4S | 4500.00 | 30 |
| 3 | Lnmia | 5000.00 | 40 |
| 4 | samsung | 4200.00 | 20 |
+----------+------------+------------+--------------+
new 的使用 mysql> create trigger alter_goods_number after insert on `order` for each row up
date goods set goods_number=goods_number-new.buy_number where goods_id=new.goods
_id;
mysql> insert into `order` values(4,'samsung',5);
old 的使用
mysql> create trigger back_goods_number after delete on `order` for each row upd
ate goods set goods_number=goods_number+old.buy_number where goods_id=old.goods_
id;
mysql> delete from `order` where goods_id=1;
更新 (update將之前下的訂單撤銷,再重新下訂單)
mysql> create trigger update_goods_number after update on `order` for each row u
pdate goods set goods_number=goods_number+old.buy_number-new.buy_number where go
ods_id=new.goods_id;
mysql> update `order` set buy_number = 10 ;