Mysql觸發器例項分析

2022-02-03 20:31:32 字數 2801 閱讀 4674

所謂觸發器,就是在定義在表物件上。當觸發器所在的表出現指定的事件時,會觸發對應表的delete update insert的操作。說的有點繞口,其實就是到監視某種情況,然後去觸發某種操作。

觸發器是如何來進行定義的呢?

在定義時要注意四個基本的語法要素:

1

1.監視地點(某張table)

22.監視事件(insert/update/delete)

33.觸發時間(觸發時的時機after/before,在事件執行之後或者在事件執行之前)

4.觸發事件(insert/update/delete)45

具體語法:

6create trigger triggername

7after/before insert/update/delete on 表名

8for each row #這句話在mysql是固定的

9begin

10sql語句;

11end;

例項的資料庫表的結構如下:

1 set foreign_key_checks=0;2

3 -- ----------------------------

4 -- table structure for

tb_goods

5 -- ----------------------------

6drop table if exists `tb_goods`;

7create table `tb_goods` (

8 `g_id` int(11) not null auto_increment comment '

商品id',

9 `goodname` varchar(20) default null comment '

商品名稱',

10 `goodcount` int(11) default null comment '

商品數目',

11primary key (`g_id`)

12 ) engine=innodb auto_increment=4 default charset=utf8;

1314

15 set foreign_key_checks=0

;16 -- ----------------------------

17 -- table structure for

tb_orders

18 -- ----------------------------

19drop table if exists `tb_orders`;

20create table `tb_orders` (

21 `o_id` int(11) not null auto_increment comment '

訂單id',

22 `g_id` int(11) default null comment '

商品id',

23 `ordercount` int(11) default null comment '

訂購數目',

24primary key (`o_id`)

25 ) engine=innodb auto_increment=4 default charset=utf8;

解決如下幾個問題:

(1)當我們向訂單表中插入資料時,會將對應的商品的數目減少對應的數量,而不用手動去更新商品的數目。

初始的商品的數目:

2#向訂單表中給商品編號為1的插入一條記錄,則對應的商品id為1的數目減2 

3 #商品的數目

(2)當我們刪除訂單表中資料時,會將對應的商品的數目恢復到對應的數量。

delete from tb_orders where g_id = 1 #刪除訂單表中 商品編號為1的訂單  則觸發商品id為2的商品數目恢復原來

(3)更新訂單資訊,則修改對應的商品的數目的資訊

對應的觸發器:

資料庫中資料變化:

update tb_orders set ordercount = 2 where g_id = 1  #更新訂單表中商品id為1的訂單的數目 則觸發商品表中數目變化 

Mysql觸發器例項分析

所謂觸發器,就是在定義在表物件上。當觸發器所在的表出現指定的事件時,會觸發對應表的delete update insert的操作。說的有點繞口,其實就是到監視某種情況,然後去觸發某種操作。觸發器是如何來進行定義的呢?在定義時要注意四個基本的語法要素 1 1.監視地點 某張table 2 2.監視事件...

mysql條件觸發器例項 mysql觸發器例項一則

例子,例項學習mysql觸發器的用法。一,準備二張測試表 1,測試表1 複製 示例 drop table if exists test create table test id bigint 11 unsigned not null auto increment,name varchar 100 n...

mysql觸發器例項

mysql從5.0開始支援觸發器 語法 create trigger 觸發器名稱 on 表名稱 for each row 觸發器sql語句 注意 在mysql中現在還不支援利用call來呼叫儲存過程 示例 比如有論壇的版塊表和文章表,乙個版塊中有多篇文章,在版塊表中有乙個字段用來記錄版塊下的文章數。...