爱游戏平台登录入口

  • Mysql爱游戏平台登录入口的触发器简略先容及利用案例
  • 2017年12月10日
  • 搜集搜集
甚么是触发器?

触发器是数据库的一个法式,他是用来监听着数据表的某个行动,一旦数据表的这个行动产生了,顿时履行响应的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 ;