递归更新触发器

时间:2012-04-20 10:15:42

标签: mysql triggers

我有这个mysql表:

CREATE TABLE IF NOT EXISTS `activities` (
`id`    INTEGER PRIMARY KEY NOT NULL AUTO_INCREMENT,
`name`  CHAR(255)   NOT NULL,
`status`    ENUM('open','progress','close'),
`date_begin`    DATE,
`date_finish`   DATE,
`progress` TINYINT,
`reliance` INTEGER,
`parent`    INTEGER,
FOREIGN KEY(owner) REFERENCES users(id) ON UPDATE CASCADE ON DELETE SET NULL,
FOREIGN KEY(reliance) REFERENCES activities(id) ON UPDATE CASCADE ON DELETE SET NULL,
FOREIGN KEY(parent) REFERENCES activities(id) ON UPDATE CASCADE ON DELETE SET NULL
)ENGINE = INNODB;

我的问题是当我想要更新一个活动的date_begin时。事实上,我想更新所有相关活动的开始日期或更新活动的子项。 我可以强制mysql创建一个递归触发器吗?

2 个答案:

答案 0 :(得分:1)

虽然触发器可能有用......创建递归触发器不是良好做法!如果你必须......那么在申请之前不要再考虑两次而是100次!它们有时会带来更多的伤害。

答案 1 :(得分:0)

这样的事情应该有效,至少如果你使用的是最新版本的MySQL:

delimiter |

CREATE TRIGGER activitiesUpdateReliantAndChildren BEFORE UPDATE ON 'activities'
FOR EACH ROW 
BEGIN 

update 'activities' 
set date_begin = NEW.date_begin 
where reliance = NEW.id;

update 'activities' 
set date_begin = NEW.date_begin 
where parent = NEW.id;

END;
|

delimiter ;