我有一个 MySQL 问题,我认为这一定很简单。当我运行以下 MySql 查询时,我需要从 table1 返回最后插入的 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 而不是 table1 的最后插入 ID,即使我插入到 table2 之间,如何才能从 table1 获取 id?
您可以将最后一个插入 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);
或者从 table1 获取最大 id(编辑:警告。请参阅 Rob Starling 的评论中关于使用最大 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 在评论中指出的那样)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)