一尘不染

LAST_INSERT_ID()MySQL

mysql

我有一个MySQL问题,我认为这很容易。当我运行以下MySql查询时,我需要从table1返回LAST INSERTED ID:

INSERT INTO table1 (title,userid) VALUES ('test',1); 
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(),4,1);
SELECT LAST_INSERT_ID();

如您所知,当前代码只会返回table2的LAST INSERT ID而不是table1,即使我插入到table2之间,也如何从table1获取ID?


阅读 265

收藏
2020-05-17

共1个答案

一尘不染

您可以将最后一个插入ID存储在变量中:

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);

或获取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;
2020-05-17