update table column after insert new record using MySQL triggers

前端 未结 3 633
庸人自扰
庸人自扰 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 22:05

    The way you are trying to set value to a column is an update. Because you are doing it after insert operation is completed.

    You actually need a before trigger.

    And to assign the same new auto incremented value of primary key column of same table, you better get it from information_schema.tables.

    Example:

    delimiter //
    drop trigger if exists bi_table_name //
    
    create trigger bi_table_name before insert on table_name
    for each row begin
      set @auto_id := ( SELECT AUTO_INCREMENT 
                        FROM INFORMATION_SCHEMA.TABLES
                        WHERE TABLE_NAME='table_name'
                          AND TABLE_SCHEMA=DATABASE() ); 
      set new.priority= @auto_id;
    end;
    //
    
    delimiter ;
    

    Note: Make sure that you don't have any pre-defined trigger with the same name and/or action. If have some, then drop them before creating the new.

    Observations:
    As per mysql documentation on last_insert_id(),

    "if you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only."

    hence, depending on last_insert_id() and auto_increment field values in batch inserts seems not reliable.

提交回复
热议问题