2009/07/13

MySQL:Insert Update Trigger

schema:testに親テーブルp01と子テーブルc01
p01.childrowsにc01のレコード数が入るイメージで、
insert,update時にtirggerを回す
***** p01 *****
CREATE TABLE `test`.`p01` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`childrows` int(11) DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=cp932;

***** c01 *****
CREATE TABLE `test`.`c01` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Chilldname` varchar(10) NOT NULL,
`pID` int(11) DEFAULT NULL,
`isDeleted` int(1) DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=cp932;

***** inset_trigger *****
delimiter //
create trigger c01_after_insert
after insert on test.c01
for each row
begin
update p01
set childrows = (select count(*) from c01 where pID = new.pID and c01.isDeleted = 0)
where ID = new.pID;
end//
delimiter ;

***** update trigger *****
delimiter //
create trigger c01_after_update
after update on test.c01
for each row
begin
if new.isDeleted <> old.isDeleted then
update p01
set childrows = (select count(*) from c01 where pID = new.pID and c01.isDeleted = 0)
where ID = new.pID;
end if;
end//
delimiter ;

0 件のコメント: