2013-04-18 155 views
0

我目前正在處理一個數據庫,該數據庫將語句存儲在兩個表中,並且有另一個將語句鏈接在一起的表。 前兩個表會自動遞增每個條目的主ID,但是我需要知道已將其輸入到鏈接它們的表中的新ID。SQL插入自動增量值

Table 1 
SID  | Statement   | Language 
1 | Have a cup of coffee  | English 
2 | Have a cup of green tea  | English 

Table 2 
AID | Action 
1 | recycle the cup 
2 | feel full of cafine 
3 | throw away the cup 
4 | feel healthy 
5 | jump 

Table 3 - relationships 

SID | AID 
1 | 1 
1 | 2 
1 | 3 
2 | 1 
2 | 3 
2 | 4 

這樣一個例子:那麼

INSERT INTO actions(Action) VALUES ('Go to the pub'); 
INSERT INTO statements(statement, Language) VALUES ('Have a pint', 'English'); 

的關係是,知道在這個例子中自動增量值是3和6:

INSERT INTO Relationships(SID,AID) VALUES (3,6); 

我需要的值3和6需要作爲變量插入,如下面的語句:

INSERT INTO Relationships(SID,AID) VALUES (id1, id2); 

回答

0

試試這個

INSERT INTO actions(Action) VALUES ('Go to the pub'); 
SET @aid = LAST_INSERT_ID(); 

INSERT INTO statements(statement, Language) VALUES ('Have a pint', 'English'); 
SET @sid = LAST_INSERT_ID(); 

INSERT INTO Relationships(SID,AID) VALUES (@sid,@aid); 
+0

感謝您的回覆! 但是,當我運行此代碼時,得到:錯誤代碼:1064.您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在第1行'declare v_aid integer,v_sid integer'附近使用正確的語法。 – Jon8672

+0

@ Jon8672,我編輯了我的代碼,嘗試更新版本 –

+0

非常感謝您的完美工作! – Jon8672