开发者

Make a query in mysql without invoking a trigger (How to disable a trigger)

I have 2 tables: comments and comments_likes.


comments

id     
message
likes  

triggers:

AFTER DELETE

DELETE FROM comments_likes WHERE comment_id = OLD.id;

comments_likes

id        
comment_id

triggers:

AFTER INSERT

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

AFTER DELETE

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

AFTER UPDATE

**omited code, updates comments**

So the question is, can I disable the triggers when activating them from another trigger?

What I want is do something l开发者_如何学Pythonikes this:

AFTER DELETE

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

[EDIT]

A non optimized solution would be (very slow query... makes a query for each LIKE register):

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

UPDATE LOW PRIORITY and IGNORE don't works.

[EDIT 2]

I have another idea, is possible to set a global variable in the first trigger and read it from the other trigger?

Ex:

first trigger:

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

other trigger:

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


To disable triggers you can do:

Trigger 1

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

Trigger 2

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


Can be a bit ugly, but what i do is rename the table to table2 which the trigger does not attach too, and then, on the end, rename back.


No you can't. That's the point of triggers: to be run always.

Besides, I can't see why you would need that in your case. At worst nothing gets updated - no errors will be raised.

You can always add a condition in your trigger, to check if they (or part of their code) should be run (for example if there is a record in relevant table).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜