2012-10-03 3 views
0

tableA와 tableB 두 개의 테이블에 행을 삽입하는 쿼리를 작성하려고합니다. tableA는 우리가 지원하는 다양한 언어로 된 email의 실제 텍스트를 tableB가 포함하는 동안 use로 보낼 수있는 전자 메일 목록입니다. tableA의 자동 증가 ID는 tableB에 저장되어 이메일 이름과 텍스트를 연결합니다.mySQL은 다음 삽입에서 새로 삽입 된 행의 ID를 사용합니다.

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

이 작업을 수행하는 방법에 대한 의견이 있으십니까?

감사

답변

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 
관련 문제