1 ) 概述
2 )用法示例
2.1 比较麻烦的sql
select
*
from
(select nid,name from tb1 where nid > 2) as A
where
A.name > 'alex'
2.2 使用视图简化以便后续可能得复用
create view v1 as select nid,name from tb1 where nid > 2
select * from v1;
select * from (select nid,name from tb1 where nid > 2) as v1
drop view v1;
alter view v1 as sql语句
1 ) 概述
2 )用法示例
2.1 插入前,插入后
-- 插入前
create trigger tri_before_insert_tb1 before insert on tb1 for each row
begin
-- ... 这里写你的逻辑
end
-- 插入后
create trigger tri_after_insert_tb1 after insert on tb1 for each row
begin
-- ... 这里写你的逻辑
end
2.2 删除前,删除后
-- 删除前
create trigger tri_before_delete_tb1 before delete on tb1 for each row
begin
-- ... 这里写你的逻辑
end
-- 删除后
create trigger tri_after_delete_tb1 after delete on tb1 for each row
begin
-- ... 这里写你的逻辑
end
2.3 更新前,更新后
-- 更新前
create trigger tri_before_update_tb1 before update on tb1 for each row
begin
-- ... 这里写你的逻辑
end
-- 更新后
create trigger tri_after_update_tb1 after update on tb1 for each row
begin
-- ... 这里写你的逻辑
end
FOR EACH ROW
是针对每一行的
drop trigger tri_after_insert_tb1;
这里删除定义的一个触发器3 )综合示例
delimiter $$
create trigger tri_before_insert_t1 before insert on t1 for each row
begin
if NEW.name = 'alex' then
insert into t2(name) values(NEW.name); -- NEW 是新插入的数据
end if;
end $$
delimiter;
delimiter $$
create trigger tri_after_insert_t1 after delete on t1 for each row
begin
if OLD.name = 'alex' then
insert into t2(id, name) values(OLD.id, OLD.name);
end if;
end $$
delimiter;
NEW
是新数据,OLD
是原数据