LAST_INSERT_ID() MySQL

后端 未结 11 2269
花落未央
花落未央 2020-11-22 10:56

I have a MySQL question that I think must be quite easy. I need to return the LAST INSERTED ID from table1 when I run the following MySql query:

INSERT INTO          


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

    This enables you to insert a row into 2 different tables and creates a reference to both tables too.

    START TRANSACTION;
    INSERT INTO accounttable(account_username) 
        VALUES('AnAccountName');
    INSERT INTO profiletable(profile_account_id) 
        VALUES ((SELECT account_id FROM accounttable WHERE account_username='AnAccountName'));
        SET @profile_id = LAST_INSERT_ID(); 
    UPDATE accounttable SET `account_profile_id` = @profile_id;
    COMMIT;
    
    0 讨论(0)
  • 2020-11-22 11:17

    It would be possible to save the last_id_in_table1 variable into a php variable to use it later?

    With this last_id I need to attach some records in another table with this last_id, so I need:

    1) Do an INSERT and get the last_id_in_table1

    INSERT into Table1(name) values ("AAA"); 
    SET @last_id_in_table1 = LAST_INSERT_ID();
    

    2) For any indeterminated rows in another table, UPDATING these rows with the last_id_insert generated in the insert.

    $element = array(some ids)    
    foreach ($element as $e){ 
             UPDATE Table2 SET column1 = @last_id_in_table1 WHERE id = $e 
        }
    
    0 讨论(0)
  • 2020-11-22 11:18

    For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;

    CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
    BEGIN
    LOCK TABLES `table1` WRITE;
    INSERT INTO `table1` ( `title` ) VALUES ( @title ); 
    SET @id = LAST_INSERT_ID();
    UNLOCK TABLES;
    INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1); 
    END
    

    And you can use it...

    SET @myid;
    CALL myproc( @myid, 1, "my title" );
    SELECT @myid;
    
    0 讨论(0)
  • 2020-11-22 11:18

    For last and second last:

    INSERT INTO `t_parent_user`(`u_id`, `p_id`) VALUES ((SELECT MAX(u_id-1) FROM user) ,(SELECT MAX(u_id) FROM user  ) );
    
    0 讨论(0)
  • 2020-11-22 11:23

    We only have one person entering records, so I execute the following query immediately following the insert:

    $result = $conn->query("SELECT * FROM corex ORDER BY id DESC LIMIT 1");
    
    while ($row = $result->fetch_assoc()) {
    
                $id = $row['id'];
    
    }
    

    This retrieves the last id from the database.

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