【问题标题】:Insert row, get id from inserted row and use it in new insert statement [duplicate]插入行,从插入的行中获取 id 并在新的插入语句中使用它[重复]
【发布时间】: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


【解决方案1】:

您可以将最后一个插入 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);    
Or get the max id frm table1

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;   

或者 我们在上面插入了 3 条记录。因此,下一个id必须是4。

下面是知道下一个id的语法。

SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "yourDatabaseName"
AND TABLE_NAME = "yourTableName"

【讨论】:

  • 请不要在没有署名的情况下从other answers复制代码。
猜你喜欢
  • 2012-03-17
  • 2010-12-11
  • 1970-01-01
  • 2017-03-27
  • 2014-01-29
  • 1970-01-01
  • 2010-11-03
  • 1970-01-01
相关资源
最近更新 更多