mysql觸發器l安全嗎 觸發器 MySQL

2021-10-18 11:58:50 字數 3394 閱讀 3206

1.需求

- 統計同一所學校的學生人數

2.建表

- 學生表(student)

drop table if exists student;

create table `student` (

`id` int not null auto_increment,

`name` varchar(100),

`age` smallint,

`school` varchar(200) not null,

primary key (`id`)

)engine = innodb default charset = utf8

- 學校人數表(school_num)

drop table if exists school_num;

create table `school_num` (

`school` varchar(200) not null,

`num` int default 0,

primary key (`school`)

)engine = innodb default charset = utf8;

3.觸發器

- add_school_num

-- 新增時更新學校人數

drop trigger if exists add_school_num;

create trigger add_school_num

after insert on `student` for each row

begin

if (new.school in (select school from school_num)) then

update school_num set num = num + 1 where school = new.school;

else

insert into school_num (school, num) values (new.school, 1);

end if;

end;

- delete_school_num

-- 刪除時更新學校人數

drop trigger if exists delete_school_num;

create trigger delete_school_num

after delete on `student` for each row

begin

if (old.school in (select school from school_num)) then

update school_num set num = num -1 where school = old.school;

end if;

end;

- update_school_num

-- 更新是更新學校人數

drop trigger if exists update_school_num;

create trigger update_school_num

after update on `student` for each row

begin

if (new.school in (select school from school_num)) then

update school_num set num = num + 1 where school = new.school;

else

insert into school_num (school, num) values (new.school, 1);

end if;

if (old.school in (select school from school_num)) then

update school_num set num = num - 1 where school = old.school;

end if;

end;

4.測試

4.1 插入資料

4.1.1 執行sql

insert into `student` (name, age, school) values ('張三', 22, '北京大學');

insert into `student` (name, age, school) values ('李四', 25, '北京大學');

insert into `student` (name, age, school) values ('王五', 21, '清華大學');

insert into `student` (name, age, school) values ('趙六', 19, '北郵大學');

4.1.2 student表資料

4.1.3 school_num表資料

4.2 刪除資料

4.2.1 執行sql

delete from `student` where name = '趙六';

4.2.2 student表資料

4.2.3 school_num表資料

4.3 更新資料(更新為已存在的學校)

4.3.1 執行sql

update `student` set school = '北郵大學' where name = '王五';

4.3.2 student表資料

4.3.3 school_num表資料

4.4 更新資料(更新為不存在的學校)

4.4.1 執行sql

update `student` set school = '傳媒大學' where name = '李四'

4.4.2 student表資料

4.4.3 school_num表資料

mysql觸發器l安全嗎 Mysql觸發器

觸發器是一種特殊的儲存過程,它在插入 刪除或修改特定表中的資料時觸發執行,它比資料庫本身標準的功能有更精細和更複雜的資料控制能力。和儲存過程一樣,很少使用。1 觸發器的作用 1.可在寫入資料表前,強制檢驗或轉換資料。2.觸發器發生錯誤時,異動的結果會被撤銷。3.部分資料庫管理系統可以針對資料定義語言...

觸發器 mysql觸發器

觸發器是一種特殊的儲存過程,它在插入 刪除或修改特定表中的資料時觸發執行,它比資料庫本身標準的功能有更精細和更複雜的資料控制能力。和儲存過程一樣,很少使用。1 觸發器的作用 2 建立觸發器 建立測試環境 mysql create database test db query ok,1 row aff...

mysql觸發器when MySQL觸發器

set quoted identifier on goset ansi nulls on goalter trigger trg risks on dbo.projectrisk for insert,update asbegin update projectrisk set classificat...