Delete the same row inserted in a table by trigger in mysql

霸气de小男生 提交于 2019-12-30 13:43:06

问题


I'm trying to remove a row after inserted in a temp table and I get this error:

INSERT INTO `temp_program_counter` (`id`, `program_id`) values (NULL, '275')

Can't update table 'temp_program_counter' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

And here is my trigger:

DELIMITER $$
DROP TRIGGER IF EXISTS `testtemp`$$

CREATE

    TRIGGER `testtemp` AFTER INSERT ON `temp_program_counter` 
    FOR EACH ROW BEGIN
        UPDATE `program` SET `view_count`=`view_count`+1;
        DELETE  FROM `temp_program_counter` WHERE id=new.id;
    END;
$$

DELIMITER ;

this table is a temp table that get's data with delay and after receiving must update the main table and be deleted from temp. thanks for helping in advance.


回答1:


You probably have already resolved this in some way but I'll post the answer anyway:

You cannot refer to the same table that triggered the trigger in a trigger (or a combination of trigger and stored procedure). This could mean an infinite loop, so sql prevents it by giving that error, resulting in always the same error.




回答2:


Try BEFORE INSERT Because, you are trying to delete a record which has just been inserted but may be not yet committed in this session. Hence you are getting the error.

If you use BEFORE INSERT, then all other record in the table with id=new.id would be deleted and the new record will be inserted successfully.

DELIMITER $$
DROP TRIGGER IF EXISTS `testtemp`$$

CREATE

    TRIGGER `testtemp` BEFORE INSERT ON `temp_program_counter` 
    FOR EACH ROW BEGIN
        UPDATE `program` SET `view_count`=`view_count`+1;
        DELETE  FROM `temp_program_counter` WHERE id=new.id;
    END;
$$

DELIMITER ;


来源:https://stackoverflow.com/questions/24258938/delete-the-same-row-inserted-in-a-table-by-trigger-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!