본문 바로가기
MySql

MySQL 트리거를 호출하지 않고 mysql에서 쿼리 만들기 (트리거를 비활성화하는 방법)

by 베이스 공부 2020. 11. 11.
반응형

comments comments_likes 라는 2 개의 테이블이 있습니다.

댓글

id     
message
likes  

트리거 :

삭제 후

DELETE FROM comments_likes WHERE comment_id = OLD.id;

좋아요 _ 댓글

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

UPDATE LOW PRIORITY IGNORE 가 작동하지 않습니다.

[수정 2]

다른 아이디어가 있습니다. 첫 번째 트리거에서 전역 변수를 설정하고 다른 트리거에서 읽을 수 있습니까?

전의:

첫 번째 트리거 :

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

다른 트리거 :

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

 

해결 방법

 

트리거를 비활성화하려면 다음을 수행하십시오.

트리거 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;

 

참조 페이지 https://stackoverflow.com/questions/3577528

 

 

반응형

댓글