我在MySQL中使用触发器存在一些问题。
假设我们有2个表:
和2个触发器:
问题是,当我删除TableB中的某些行时,TriggerB触发并删除TableA中的某些元素,然后TriggerA触发并尝试更新TableB。
它失败,因为TriggerA尝试更新TableB中正在删除的某些行。
如何避免这种循环依赖性?
这两个触发器都不是没有用的,所以我不知道我应该怎么做才能解决这个问题。
尝试使用变量。
第一次触发:
CREATE TRIGGER trigger1 BEFORE DELETE ON table1 FOR EACH ROW BEGIN IF @deleting IS NULL THEN SET @deleting = 1; DELETE FROM table2 WHERE id = OLD.id; SET @deleting = NULL; END IF; END
第二个触发条件:
CREATE TRIGGER trigger2 BEFORE DELETE ON table2 FOR EACH ROW BEGIN IF @deleting IS NULL THEN SET @deleting = 1; DELETE FROM table1 WHERE id = OLD.id; SET @deleting = NULL; END IF; END
以及其他AFTER DELETE触发器:
CREATE TRIGGER trigger3 AFTER DELETE ON table1 FOR EACH ROW BEGIN SET @deleting = NULL; END CREATE TRIGGER trigger4 AFTER DELETE ON table2 FOR EACH ROW BEGIN SET @deleting = NULL; END