在不调用触发器的情况下在mysql中进行查询(如何禁用触发器)

时间:2010-08-26 17:02:25

标签: mysql triggers myisam

我有2个表:commentscomments_likes


评论

id     
message
likes  

触发器

删除后

DELETE FROM comments_likes WHERE comment_id = OLD.id;

comments_likes

id        
comment_id

触发器

插入后

UPDATE comments SET likes = likes + 1 WHERE comments.id = NEW.comment_id;

删除后

UPDATE comments SET likes = likes - 1 WHERE comments.id = OLD.comment_id;

更新后

**omited code, updates comments**

所以问题是,我可以在从其他触发器激活触发器时禁用触发器吗?

我想做的是做这样的事情:

删除后

IF NOT called_from_another_trigger() THEN
    UPDATE comments SET likes = likes - 1 WHERE comments.id = OLD.comment_id;
END IF;

[编辑]

非优化的解决方案是(非常慢的查询...对每个LIKE寄存器进行查询):

BEGIN
    IF (SELECT id FROM comments WHERE comments.id = OLD.comment_id) THEN
        UPDATE comments SET comments.cache_likes = comments.cache_likes - 1 WHERE comments.id = OLD.comment_id;
    END IF;
END

更新LOW PRIORITYIGNORE不起作用。

[编辑2]

我有另外一个想法,可以在第一个触发器中设置一个全局变量并从另一个触发器中读取它吗?

例如:

第一次触发:

@disable_triggers = true;
// do the stuff that calls another triggers
@disable_triggers = false;

其他触发器:

if @disable_triggers = false then
    // do the stuff
end if;

3 个答案:

答案 0 :(得分:23)

要禁用触发器,您可以执行以下操作:

触发1

SET @disable_trigger = 1;
// do stuff that calls trigger 2
SET @disable_trigger = NULL;

触发2

IF @disable_trigger IS NULL THEN
    // do stuff only if called from a query and not from trigger 1
END IF;

答案 1 :(得分:1)

可能有点难看,但我所做的是将表重命名为table2,触发器也没有附加,然后,最后重命名。

答案 2 :(得分:0)

不,你不能。这就是触发点:永远运行。

此外,我无法理解你为什么需要这种情况。最糟糕的是什么都没有得到更新 - 不会出现任何错误。

您始终可以在触发器中添加条件,以检查它们(或部分代码)是否应该运行(例如,如果相关表中有记录)。