Du måste använda 2 triggers för att uppnå detta.
- efter uppdatering om barn
- efter borttagning på barn
Exempel 1 :Efter UPPDATERING :
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 ;
Exempel 1 :Efter DELETE :
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 ;