問題描述
我有一個 MySQL 問題,我認為它一定很簡單.當我運行以下 MySql 查詢時,我需要從 table1 返回 LAST INSERTED ID:
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 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?
As you can understand the current code will just return the LAST INSERT ID of table2 instead of table1, how can I get the id from table1 even if I insert into table2 between?
推薦答案
您可以將最后一個插入 id 存儲在一個變量中:
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);
或者從 table1 中獲取最大 id(警告.請參閱 Rob Starling 評論中的注釋,關于使用最大 id 時競爭條件可能導致的錯誤)
Or get the max id from table1 ( Warning. See note in comments from Rob Starling about possible errors from race conditions when using the max id)
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;
(警告:正如 Rob Starling 在
(Warning: as Rob Starling points out in the
這篇關于LAST_INSERT_ID() MySQL的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!