LAST_INSERT_ID() MySQL

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

提交回复
热议问题