2012-10-03 39 views
0

我想寫一個查詢,將行插入到兩個表,表A和tableB的。表A是可以被髮送到使用電子郵件的列表,同時tableB的包含電子郵件,說在我們所支持的各種語言的實際文本。從表A自動遞增ID獲取存儲TableB中的電子郵件名稱與文本連接。MySQL的使用來自新插入的行ID在明年插入

什麼是抓住從插入到TABLEA然後插入到tableB的查詢使用新行的ID的最佳方式?我試過,但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'); 

如何使這項工作有什麼想法?

感謝

回答

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'); 
+0

真棒,這是正是我需要的。謝謝 – baiano

0

也許LAST_INSERT_ID()是否行得通呢?

嘗試一些形式:

insert INTO tableB(...) 
    SELECT LAST_INSERT_ID(), 'literals' from TableA