MySQL - Trigger for updating same table after insert

前端 未结 6 1676
长情又很酷
长情又很酷 2020-11-22 15:39

Here\'s what I\'m trying to do:

When there\'s a new INSERT into the table ACCOUNTS, I need to update the row in ACCOUNTS where

相关标签:
6条回答
  • 2020-11-22 16:01

    It seems that you can't do all this in a trigger. According to the documentation:

    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.

    According to this answer, it seems that you should:

    create a stored procedure, that inserts into/Updates the target table, then updates the other row(s), all in a transaction.

    With a stored proc you'll manually commit the changes (insert and update). I haven't done this in MySQL, but this post looks like a good example.

    0 讨论(0)
  • 2020-11-22 16:02

    Had the same problem but had to update a column with the id that was about to enter, so you can make an update should be done BEFORE and AFTER not BEFORE had no id so I did this trick

    DELIMITER $$
    DROP TRIGGER IF EXISTS `codigo_video`$$
    CREATE TRIGGER `codigo_video` BEFORE INSERT ON `videos` 
    FOR EACH ROW BEGIN
        DECLARE ultimo_id, proximo_id INT(11);
        SELECT id INTO ultimo_id FROM videos ORDER BY id DESC LIMIT 1;
        SET proximo_id = ultimo_id+1;
        SET NEW.cassette = CONCAT(NEW.cassette, LPAD(proximo_id, 5, '0'));
    END$$
    DELIMITER ;
    
    0 讨论(0)
  • 2020-11-22 16:04
    DELIMITER $$
    
    DROP TRIGGER IF EXISTS `setEditStatus`$$
    CREATE TRIGGER `setEditStatus` **BEFORE** INSERT on ACCOUNTS
    FOR EACH ROW BEGIN
    
        SET NEW.STATUS = 'E';
    
    END$$
    
    DELIMITER ;
    
    0 讨论(0)
  • 2020-11-22 16:11

    On the last entry; this is another trick:

    SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_schema = ... and table_name = ...
    
    0 讨论(0)
  • 2020-11-22 16:15

    Instead you can use before insert and get max pkid for the particular table and then update the maximium pkid table record.

    0 讨论(0)
  • 2020-11-22 16:17

    This is how I update a row in the same table on insert

    activationCode and email are rows in the table USER. On insert I don't specify a value for activationCode, it will be created on the fly by MySQL.

    Change username with your MySQL username and db_name with your db name.

    CREATE DEFINER=`username`@`localhost` 
           TRIGGER `db_name`.`user_BEFORE_INSERT` 
           BEFORE INSERT ON `user` 
           FOR EACH ROW
             BEGIN
                SET new.activationCode = MD5(new.email);
             END
    
    0 讨论(0)
提交回复
热议问题