2015-11-11 16 views
1

我具有表A(與AI PK)一組行的,我想基於特定標準來克隆,即:MySQL的:在表克隆在表A中的多個行和相關行乙

INSERT INTO A(field1,field2,field3)SELECT field1,field2,field3 FROM A WHERE(criteria)

但是,這些行與Table B有1-1的關係,它們在B中具有AI PK,在A中具有FK。我還想克隆表B中的相關行,並將A中的克隆行指向B中的克隆行而不是原始行。

我正在尋找最簡單的方法來做到這一點 - 最好只是在SQL中。

這裏是什麼,我試圖做一個例子:

前CLONE:

Table A 
ID B_FK Other Data Meets Clone Criteria  
1 101 Data 1  true 
2 102 Data 2  false 
3 103 Data 3  true 
4 104 Data 4  true 

Table B 
ID Other Data 
101 Data A 
102 Data B 
103 Data C 
104 Data D 

AFTER行CLONING:

Table A 
ID B_FK Other Data 
1 101 Data 1 
2 102 Data 2 
3 103 Data 3 
4 104 Data 4 
5 105 Data 1 
6 106 Data 3 
7 107 Data 4 

Table B 
ID Other Data 
101 Data A 
102 Data B 
103 Data C 
104 Data D 
105 Data A 
106 Data C 
107 Data D 
+0

這個問題解決了在SQL Server中同樣的問題 - 但我被堵在MySQL:http://stackoverflow.com/questions/5365629/using-merge-output-to-get- mapping-between-source-id-and-target-id – scotru

+0

下面是一個與存儲相關的問題過程做單行 - 但我想做一整行的行:http://stackoverflow.com/questions/6767066/copy-row-and-all-of-its-children – scotru

回答

1

下面是一個使用子查詢複製表B中的行,讓他們點在表中的

insert into b (a_fk, some_field) 
select 
    (select max(a2.id) from a a2 
    where a2.id <> a1.id 
    and a2.field1 = a1.field1 
    and a2.field2 = a1.field2 
    and a2.field3 = a1.field3), 
    b.some_field 
from b 
join a a1 on a1.id = b.a_fk 
where (criteria) 

新FK的方式,但它可能更容易,速度更快,以創建一個包含附加列源ID

insert into a (field1, field2, field3, source_id) 
select field1, field2, field3, id 
from a where (criteria) 

insert into b (a_fk, some_field) 
select a.id, b.some_field 
from b 
join a on a.source_id = b.a_fk 
where (criteria) 
+0

表中有很多列,第一種方法是'太吸引人了(我也想要一個更可重用的解決方案)。根據您的建議添加一列可能確實是一個很好的解決方案。我認爲這也可以用MySQL遊標完成?我正試圖現在探索這種方法。 – scotru

+0

我使用了額外的列方法 – scotru

1

SET FOREIGN_KEY_CHECKS=0 然後做任何你需要用INSERT INTO ... SELECT 如果還有更多事情需要外鍵檢查 SET FOREIGN_KEY_CHECKS=1

+0

問題是我需要TABLE A中的克隆行爲TABLE B中新克隆的行提供正確的外鍵。 – scotru

+0

您能用一個例子來說明嗎?特別是,爲什麼只將A行插入到B中將不起作用。 –

+0

是的,我已經編輯了上面的問題。我不想克隆從A到B的行。我試圖克隆A到A中的行,同時也克隆B中相關的子行到B. – scotru