得到错误1442试图触发更新

时间:2015-04-30 08:05:42

标签: mysql triggers mysql-error-1442

我尝试在更新发生时将chatroompost.view的更新从1更新为0 chatroompost.likecount <= -5

CREATE TRIGGER `chatroompost_AFTER_UPDATE` 
AFTER UPDATE ON `chatroompost` 
FOR EACH ROW BEGIN  
    IF (NEW.likecount <= -5) THEN
        UPDATE `chatroompost` SET NEW.`view`='0'  WHERE `chatroompost`.`idchatroompost` = OLD.`idchatroompost`;   
    END IF;  
END $$ 
DELIMITER ;

查询:

UPDATE `chatroompost` SET likecount='-11' WHERE idchatroompost=1; SELECT *FROM chatroompost;

但我得到了

  

错误代码:1442。无法在存储的函数/触发器中更新表'chatroompost',因为它已被调用此存储函数/触发器的语句使用。

我尝试REPLACE AFTERBEFORE,但仍然遇到同样的错误。

1 个答案:

答案 0 :(得分:0)

解决方案:使其成为BEFORE UPDATE ON触发器,并使用NEW运算符,它将完成这项工作。

DROP TRIGGER IF EXISTS`chatroompost_AFTER_UPDATE` ; 
DELIMITER $$ 
use mydb $$

CREATE TRIGGER `chatroompost_AFTER_UPDATE` 
BEFORE UPDATE ON `chatroompost` 
FOR EACH ROW BEGIN  
    IF (NEW.likecount <= -5) THEN
        NEW.view='0';   
    END IF;  
END $$ 
DELIMITER ;  

原因:您无法更新调用触发器的表(chatroompost):

  

在存储的函数或触发器中,不允许修改a   已经被使用(用于读或写)的表   调用函数或触发器的语句。

这样做会产生错误1442:

Error Code: 1442
Can't update table 'chatroompost' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.