_INSERT_ID()MySQL我有一個MySQL問題,我認為這個問題一定很簡單。在運行以下MySQL查詢時,需要從表1返回最后插入的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();正如您所理解的,當前代碼將只返回表2的最后一個插入ID,而不是表1,即使在表2之間插入到表2中,我如何從表1獲得id?
3 回答

開滿天機
TA貢獻1786條經驗 獲得超13個贊
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);
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/150
提交
取消