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

前端 未结 2 1321
忘掉有多难
忘掉有多难 2021-01-17 05:43

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\         


        
相关标签:
2条回答
  • 2021-01-17 06:25

    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.

    0 讨论(0)
  • 2021-01-17 06:29

    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 ;
    
    0 讨论(0)
提交回复
热议问题