【发布时间】:2020-01-14 11:16:28
【问题描述】:
有没有办法插入一行,获取插入的 id 并在下一个查询中使用它?所有这些都在一个查询中完成?
INSERT INTO tableA (eID, name, otherStuff) VALUES (NULL, 'emailName', 'otherValues');
SET @tableA_id = SELECT LAST_INSERT_ID();
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, @tableA_id, 'email text', 'Default', '1');
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, @tableA_id, 'other language text', 'Default', '2');
在前面的代码段中,有三个单独的查询,当我在我的 sql 编辑器中执行它们时,这里给我一个错误:SET @tableA_id = LAST_INSERT_ID();
同样,这里有 3 个单独的查询,有没有办法使用子查询之类的东西来实现这一点?
【问题讨论】:
-
错误是什么?你是先声明变量吗?您可以在 eID 字段中插入 null 吗?我们需要错误详情
-
@Brad 没有具体错误。这就是我要返回的内容:
[ERROR in query 2] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()' at line 1 -
但是,您在问题中提出的块中没有代码
SELECT LAST_INSERT_ID()。 -
是的,有@BarbarosÖzhan,它在第一个
INSERT INTO之后。第二行 -
不,那是
SET @tableA_id = LAST_INSERT_ID();
标签: mysql sql sql-insert