update table column after insert new record using MySQL triggers

前端 未结 3 628
庸人自扰
庸人自扰 2020-12-18 21:48

Imagine I have a MySQL table (tbl_test) with these fields: id, title, priority.
id will be incremented automatically. I need to fill

3条回答
  •  情歌与酒
    2020-12-18 21:56

    I don't think you can do that. An AFTER INSERT trigger cannot modify the same table, neither by issuing an UPDATE nor by something like this:

    DROP TRIGGER new_tbl_test;
    
    DELIMITER $$
    
    CREATE TRIGGER new_tbl_test 
    AFTER INSERT ON tbl_test for each row
    begin
    UPDATE tbl_test SET priority = new.id WHERE id = new.id;
    END $$
    
    DELIMITER ;
    

    It gives error like

    ERROR 1442 (HY000): Can't update table 'tbl_test' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
    

    What you can do, is use a transaction:

    Example : Table structure is like below

    mysql> show create table tbl_test\G
    *************************** 1. row ***************************
           Table: tbl_test
    Create Table: CREATE TABLE `tbl_test` (
      `ID` int(11) NOT NULL AUTO_INCREMENT,
      `title` char(30) DEFAULT NULL,
      `priority` int(11) DEFAULT NULL,
      PRIMARY KEY (`ID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    1 row in set (0.00 sec)
    

    Transaction

    START TRANSACTION ;
      INSERT INTO tbl_test (title)
        VALUES ('Dr');
      UPDATE tbl_test
        SET `priority` = id
        WHERE id = LAST_INSERT_ID();
    COMMIT ;
    

    Check data

    mysql> SELECT * FROM tbl_test;
    +----+-------+----------+
    | ID | title | priority |
    +----+-------+----------+
    |  1 | Dr    |        1 |
    +----+-------+----------+
    1 row in set (0.00 sec)
    

提交回复
热议问题