How to Update same table on deletion in MYSQL?

前端 未结 2 1945
滥情空心
滥情空心 2020-12-09 05:12

In my database I have a table Employee that has recursive association (an employee can be boss of other employee):

create table if not exists `e         


        
相关标签:
2条回答
  • 2020-12-09 05:43

    Instead of doing a hard delete, do a soft delete. Add is_deleted column and set it to 1 if you want to delete the row. Create after_update trigger on the table.

    DELIMITER $$
        CREATE
        TRIGGER `Employee_after_update` AFTER UPDATE
          ON `Employee`
          FOR EACH ROW BEGIN
          UPDATE Employee
          ...............
          WHERE NEW.is_deleted=1; 
          DELETE FROM Employee WHERE NEW.is_deleted=1
        END$$
    

    I am not sure that you can update the same table for after_{insert,delete,update}. Please check this

    0 讨论(0)
  • 2020-12-09 05:52

    Use a stored procedure:

    UPDATE b
       SET b.mssn = a.mssn
      FROM EMPLOYEE a
      JOIN EMPLOYEE b ON b.mssn = a.ssn
     WHERE a.ssn = @deletedBoss
    
    DELETE FROM employee WHERE ssn = @deletedBoss
    

    With a stored procedure, you can simply delete the rows you want, and after that, update the same table. That should prevent the error message.

    0 讨论(0)
提交回复
热议问题