LAST_INSERT_ID() MySQL

后端 未结 11 2267
花落未央
花落未央 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: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;
    

提交回复
热议问题