Using Auto-Increment value in MYSQL Before Insert Trigger?

前端 未结 4 728
我寻月下人不归
我寻月下人不归 2020-12-10 04:36

The users table:

CREATE TABLE `users` (
  `id` int(8) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(45) DEFAULT NULL,
  `username` varchar(16) DEFAULT          


        
4条回答
  •  甜味超标
    2020-12-10 05:11

    OP's comment:
    How would I do it before, thou?

    You can find current auto_increment value that is to be assigned to a new record.
    And use the same in the before trigger as a parent user id for user_records table.
    You have to query information_schema.tables table to find the value.

    Example:

    use `gknet`;
    
    delimiter $$
    
    drop trigger if exists before_create_user; $$
    
    create definer=`root`@`localhost` trigger `before_create_user` 
           before insert on `users` 
    for each row begin
      declare fk_parent_user_id int default 0;
    
      select auto_increment into fk_parent_user_id
        from information_schema.tables
       where table_name = 'users'
         and table_schema = database();
    
      insert into user_records ( action, userid, timestamp )
             values ( 'created', fk_parent_user_id, now() );
    end;
    
    $$
    
    delimiter ;
    

    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.

提交回复
热议问题