LAST_INSERT_ID() MySQL

后端 未结 11 2268
花落未央
花落未央 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 10:59

    Just to add for Rodrigo post, instead of LAST_INSERT_ID() in query you can use SELECT MAX(id) FROM table1;, but you must use (),

    INSERT INTO table1 (title,userid) VALUES ('test', 1)
    INSERT INTO table2 (parentid,otherid,userid) VALUES ( (SELECT MAX(id) FROM table1), 4, 1)
    
    0 讨论(0)
  • 2020-11-22 11:01

    If you need to have from mysql, after your query, the last auto-incremental id without another query, put in your code:

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

    You could store the last insert id in a variable :

    INSERT INTO table1 (title,userid) VALUES ('test', 1); 
    SET @last_id_in_table1 = LAST_INSERT_ID();
    INSERT INTO table2 (parentid,otherid,userid) VALUES (@last_id_in_table1, 4, 1);    
    

    Or get the max id frm table1

    INSERT INTO table1 (title,userid) VALUES ('test', 1); 
    INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(), 4, 1); 
    SELECT MAX(id) FROM table1;   
    
    0 讨论(0)
  • 2020-11-22 11:02

    Instead of this LAST_INSERT_ID() try to use this one

    mysqli_insert_id(connection)
    
    0 讨论(0)
  • 2020-11-22 11:06

    I had the same problem in bash and i'm doing something like this:

    mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');"
    

    which works fine:-) But

    mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');set @last_insert_id = LAST_INSERT_ID();"
    mysql -D "dbname" -e "insert into table2 (id_tab1) values (@last_insert_id);"
    

    don't work. Because after the first command, the shell will be logged out from mysql and logged in again for the second command, and then the variable @last_insert_id isn't set anymore. My solution is:

    lastinsertid=$(mysql -B -N -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');select LAST_INSERT_ID();")
    mysql -D "dbname" -e "insert into table2 (id_tab1) values (${lastinsertid});"
    

    Maybe someone is searching for a solution an bash :-)

    0 讨论(0)
  • 2020-11-22 11:08

    Since you actually stored the previous LAST_INSERT_ID() into the second table, you can get it from there:

    INSERT INTO table1 (title,userid) VALUES ('test',1); 
    INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(),4,1);
    SELECT parentid FROM table2 WHERE id = LAST_INSERT_ID();
    
    0 讨论(0)
提交回复
热议问题