Mysql中的觸發器簡略引見及應用案例。本站提示廣大學習愛好者:(Mysql中的觸發器簡略引見及應用案例)文章只能為提供參考,不一定能成為您想要的結果。以下是Mysql中的觸發器簡略引見及應用案例正文
甚麼是觸發器?
觸發器是數據庫的一個法式,他是用來監聽著數據表的某個行動,一旦數據表的這個行動產生了,立時履行響應的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 ;