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

開滿天機(jī)
TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
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;
添加回答
舉報(bào)
0/150
提交
取消