我在MySQL中使用触发器时遇到了一些问题。
假设我们有2个表:
和2个触发器:
问题是,当我删除TableB中的某些行时,TriggerB会触发并删除TableA中的某些元素,然后触发TriggerA并尝试更新TableB。
失败是因为TriggerA尝试更新TableB中正在删除的某些行。
如何避免这种循环依赖?
这两个触发器都没用,所以我不知道我该怎么做才能解决这个问题。
答案 0 :(得分:8)
尝试使用变量。
第一次触发:
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