九、触发器
CREATE DATABASE d;
USE d;
--创建d1,d2,d3,d4四个空表,装触发时的数据
--表1
CREATE TABLE d1
(
id TINYINT UNSIGNED NOT NULL,
score INT UNSIGNED NOT NULL
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--表2
CREATE TABLE d2
(
id TINYINT UNSIGNED NOT NULL,
score INT UNSIGNED NOT NULL
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--表3
CREATE TABLE d3
(
id TINYINT UNSIGNED NOT NULL,
score INT UNSIGNED NOT NULL
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--表4
CREATE TABLE d4
(
id TINYINT UNSIGNED NOT NULL,
score INT UNSIGNED NOT NULL
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
--创建触发器
格式:create trigger trigger_name trigger_time(before/after) trigger_event(insert/update/delete)
on tablename(要进行操作的表) for each row(此句存在,才有new和old,如下)
insert update delete
old null old.data old.data
new nwe.data new.data null
--创建插入触发器
DELIMITER //
CREATE TRIGGER t BEFORE INSERT ON d1 FOR EACH ROW
BEGIN
INSERT INTO d2 VALUE(new.id,new.score); --向d1插入数据时,并将新数据插入到d2
END//
DELIMITER ;
--创建修改触发器
DELIMITER //
CREATE TRIGGER t2 BEFORE UPDATE ON d2 FOR EACH ROW
BEGIN
INSERT INTO d3 VALUE(old.id,old.score); --修改d2数据时,将原有的数据插入到d3
INSERT INTO d4 VALUE(new.id,new.score); --将新数据插入到d4
END//
DELIMITER ;
----创建删除触发器
DELIMITER //
CREATE TRIGGER t3 BEFORE DELETE ON d3 FOR EACH ROW
BEGIN
INSERT INTO d1 VALUE(old.id,old.score); --删除d3数据时,将原有的数据插入到d1
END//
DELIMITER ;
--查看各表数据
SELECT * FROM d1;
SELECT * FROM d2;
SELECT * FROM d3;
SELECT * FROM d4;
--向d1插入数据
INSERT INTO d1 VALUES(1,60),(2,70),(3,80),(4,90);
--修改d2的数据
UPDATE d2 SET id=5,score=20 WHERE id=1;
UPDATE d2 SET id=6,score=30 WHERE id=2;
UPDATE d2 SET id=7,score=40 WHERE id=3;
UPDATE d2 SET id=8,score=50 WHERE id=4;
--删除d3的某些数据
DELETE FROM d3 WHERE id=1;
--删除触发器
DROP TRIGGER t2;