mysql - 尝试触发更新时出现错误 1442

标签 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;

但是我得到了

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.

我试过REPLACE所有AFTERBEFORE但仍然有同样的错误。

最佳答案

解决方案:将其设置为 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 ;  

原因:您无法更新调用触发器的表(聊天室帖子):

Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

这样做会产生错误 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.

关于mysql - 尝试触发更新时出现错误 1442,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29962309/

相关文章:

php - 如何从 LAST_INSERT_ID (`my_column` +1) 获取表达式的值?

mysql - 我们可以在 mysql 的单个表上有多个触发器吗

mysql - 错误 1442 : Can't update table in stored function/trigger

MySQL 触发器 : is it possible to delete rows if table become too large?

mysql After insert trigger on table 1 that insert in table 2 具有更新表 1 的插入后触发器

php - MySQL 尝试执行 JOINed 查询时抛出错误消息

MySQL 错误 1215 (HY000) : Cannot add foreign key constraint state_id

sql - MySql:根据列重复值删除表行?

svn - 如何配置 Jenkins 流水线以通过轮询 SubVersion 来触发?

database - 在 PostgreSQL 中禁用自动提交以创建触发器