MySQL触发器案例分析及before与after的区别(2)

另一个需求是需要当对表blocks_infos做相关处理的时候,会触发另一个表bidinfo.v_publish_info 做相应的处理,因为前面已经建立了after insert on blocks_infos,不能再建立 after insert

on blocks_infos,所以只能创建 before insert on blocks_infos,如下创建了三个:

1)insert

DELIMITER $

create trigger tri_insert_blocks_infos1 before insert

on blocks_infos for each row

begin

DECLARE d int;

set d=(select intc from bidinfo.v_publish_info where id=new.infos_id);

if d is null then

update bidinfo.v_publish_info set intc=1 where id= new.infos_id;

else

update bidinfo.v_publish_info set intc=intc+1 where id= new.infos_id;

end if;

end $

DELIMITER ;

2)delete

DELIMITER $

create trigger tri_delete_blocks_infos1 before delete

on blocks_infos for each row

begin

DECLARE h int;

set h=(select intc from bidinfo.v_publish_info where id=old.infos_id);

if h is null then

update bidinfo.v_publish_info set intc=1 where id= old.infos_id;

else

update bidinfo.v_publish_info set intc=intc+1 where id= old.infos_id;

end if;

end $

DELIMITER ;

3)update ,注意可以只用两个if循环!

DELIMITER $

create trigger tri_update_blocks_infos1 before update

on blocks_infos for each row

begin

DECLARE j int;

DECLARE i int;

set i=(select intc from bidinfo.v_publish_info where id=new.infos_id);

set j=(select intc from bidinfo.v_publish_info where id=old.infos_id);

if j is null then

update bidinfo.v_publish_info set intc=1 where id= old.infos_id;

else

update bidinfo.v_publish_info set intc=intc+1 where id= old.infos_id;

end if;

if i is null then

update bidinfo.v_publish_info set intc=1 where id= new.infos_id;

else

update bidinfo.v_publish_info set intc=intc+1 where id= new.infos_id;

end if;

end $

DELIMITER ;

小结:触发器中的new和old,可以理解为处理过的整行数据,可以通过new.字段名来取出那个字段的值,并且alter和before都不能修改old的值,但是before可以修改new的值,还需要注意对同一个表的相同触发时间(after/before)的相同触发事件(insert/update/delete),只能定义一个触发器,并且before的形式的触发器需要保证触发端和被触发端都得成功才能成功!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/567444f6f238a0c15196c8d9cfc8d5f5.html