如何避免MySQL中的循环触发器依赖
作者:互联网
我在MySQL中使用触发器有一点问题.
假设我们有2个表:
>表A
>表B.
和2个触发器:
> TriggerA:在TableA上删除时触发并更新TableB
> TriggerB:在TableB上删除时触发并在TableA中删除
问题是当我删除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
标签:mysql,triggers,circular-dependency 来源: https://codeday.me/bug/20190609/1208201.html