2016-03-08 73 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