Mysql 基于子表计数更新父列的触发器
我有一张桌子叫:Mysql 基于子表计数更新父列的触发器,mysql,Mysql,我有一张桌子叫: Home HomeID, HomeAddress, Capacity. 另一个例子是: Children ChildID, HomeID,Childname. 是否有一种方法可以使用每个主表容量列作为外键链接到children表中的子表的数量自动更新该列?为此,您必须使用两个触发器 关于儿童的最新情况 删除关于儿童的内容后 示例1:更新后: delimiter // drop trigger if exists au_on_children // create tr
Home
HomeID, HomeAddress, Capacity.
另一个例子是:
Children
ChildID, HomeID,Childname.
是否有一种方法可以使用每个主表容量列作为外键链接到children表中的子表的数量自动更新该列?为此,您必须使用两个触发器
delimiter //
drop trigger if exists au_on_children //
create trigger au_on_children after update on children
for each row
begin
declare old_totalCapacity int not null default 0;
declare new_totalCapacity int not null default 0;
select
case when homeID = OLD.homeID
then sum( OLD.homeID )
else sum( homeID )
end
into old_totalCapacity ,
case when homeID = NEW.homeID
then sum( NEW.homeID )
else sum( homeID )
end
into new_totalCapacity
from children;
update home
set capacity =
case when homeID = OLD.homeID
then old_totalCapacity
else capacity
end ,
case when homeID = NEW.homeID
then new_totalCapacity
else capacity
end ;
end;
//
delimiter ;
delimiter //
drop trigger if exists ad_on_children //
create trigger ad_on_children after delete on children
for each row
begin
declare totalCapacity int not null default 0;
select sum( homeID )
into totalCapacity
from children
where homeID = OLD.homeID;
update home
set capacity = totalCapacity
where homeId = OLD.homeID;
end;
//
delimiter ;
示例1:删除后:
delimiter //
drop trigger if exists au_on_children //
create trigger au_on_children after update on children
for each row
begin
declare old_totalCapacity int not null default 0;
declare new_totalCapacity int not null default 0;
select
case when homeID = OLD.homeID
then sum( OLD.homeID )
else sum( homeID )
end
into old_totalCapacity ,
case when homeID = NEW.homeID
then sum( NEW.homeID )
else sum( homeID )
end
into new_totalCapacity
from children;
update home
set capacity =
case when homeID = OLD.homeID
then old_totalCapacity
else capacity
end ,
case when homeID = NEW.homeID
then new_totalCapacity
else capacity
end ;
end;
//
delimiter ;
delimiter //
drop trigger if exists ad_on_children //
create trigger ad_on_children after delete on children
for each row
begin
declare totalCapacity int not null default 0;
select sum( homeID )
into totalCapacity
from children
where homeID = OLD.homeID;
update home
set capacity = totalCapacity
where homeId = OLD.homeID;
end;
//
delimiter ;