mySQL在下一个插入中使用新插入行中的id

时间:2012-10-03 18:20:51

标签: mysql

我正在尝试编写一个将行插入两个表tableA和tableB的查询。 tableA是可以发送到使用的电子邮件列表,而tableB包含我们支持的各种语言的所述电子邮件的实际文本。 tableA中的自动增量ID存储在tableB中,用于将电子邮件名称与文本连接。

从插入tableA的新行中获取id然后在插入tableB的查询中使用的最佳方法是什么?我试过这个,但mySQL不喜欢它(错误1064):

INSERT INTO tableA (eID, name, otherStuff) VALUES (NULL, 'emailName', 'otherValues');
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, select max(tableA.eID) from tableA, 'email text', 'Default', '1');
INSERT INTO tableB (id, emailId, body, name, langId) VALUES (NULL, select max(tableA.eID) from tableA, 'other language text', 'Default', '2');

有关如何使这项工作的任何想法?

感谢

3 个答案:

答案 0 :(得分:3)

使用LAST_INSERT_ID()。它返回给予新行的最后一个ID(在当前连接处)。

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

答案 1 :(得分:1)

mysql函数LAST_INSERT_ID()将返回最后插入行的id。

所以你可以试试

INSERT INTO tableA (eID, name, otherStuff) VALUES (NULL, 'emailName', 'otherValues');
SET @tableA_id = 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');

答案 2 :(得分:0)

也许LAST_INSERT_ID()可行吗?

尝试以下形式:

insert INTO tableB(...)
  SELECT LAST_INSERT_ID(), 'literals' from TableA
相关问题