2016-03-08 72 views
1

我有4個表他們tbl_A,tbl_A_detail(有A_ID),tbl_B,tbl_B_detail(有B_ID),我已經做了一個「功能」返回GenerateCode插入父母與子女表從另一個表的Mysql

我想插入到tbl_A中,值來自tbl_B但帶有新的ID。 因此,這將是這樣的:

tbl_B#1行(GX-110, '羅尼')

tbl_B_detail(#1)#1行(GXD-421, '夾克' ,GX-110)

tbl_B_detail(#1)#2行(GXD-421, '帽子',GX-110)

tbl_B#2行(GX-111, '約瑟夫')

tbl_B_detail(#2)#1行(GXD-512 '太陽眼鏡',GX-111)

tbl_B_detail(#2)#2行(GXD-3623, '組織',GX-111)

我想這些記錄移動到tbl_A(結構相同),但新generate_id FOR tbl_A

的話,我想從tbl_B_detail新generate_id插入tbl_A_detail FOR tbl_A

INSERT INTO tbl_A (A_id, a_name, ...) SELECT (SELECT (Generate Code Here)), b.name FROM tbl_b

insert into tbl_A_detail(A_detail_id, A_detail_name, A_parent_id) SELECT (SELECT GenerateCode()), B_detail_name, (GeneratedCode FROM inserted Record) FROM tbl_B_detail

我怎樣才能做到這一點? #i對不起我的英文不好

回答

0

你的表應該支持事務,例如InnoDB。

SET autocommit=0; 
begin; 
set @generated_id=(Generate Code Here); 
insert into table_a (id,title) select @generated_id, title from table_b where id=4; 
insert into table_a_detail (id,detail) select @generated_id, detail from table_b_detail where id=4; 
commit; 
+0

但先生,我想將所有記錄從tbl_B,tbl_B_detail轉移到tbl_A,tbl_A_detail(不只是1條記錄)。我試過你的代碼,但是我得到了一個錯誤消息「重要的主要重複條目」。你有什麼建議嗎? – Birdie21

+0

您應該檢查生成的ID是否存在於table_a中,然後才能使用。 – chenyb999

+0

試試這個:'SET autocommit = 0; 開始; 重複 set @ generated_id =(這裏生成代碼); 從table_a中選擇count(*)到@id_count中,其中id = @ generated_id; \t直到@id_count = 0; 結束重複; insert into table_a(id,title)select @generated_id,title_bap_b where id = 4; insert into table_a_detail(id,detail)select @generated_id,table_b_detail的詳細信息,其中id = 4; 承諾; ' – chenyb999