簡體   English   中英

MySQL:克隆表A中的多行和表B中的相關行

[英]MySQL: Clone multiple rows in Table A and related rows in Table B

我要根據某些條件克隆表A中的一組行(帶有AI PK),即:

將A插入A(字段1,字段2,字段3)從一個地方選擇字段1,字段2,字段3(條件)

但是,這些行與表B具有1-1關系,表B在B中具有AI PK,而在A中具有FK。我也想克隆表B中的相關行,並使A中的克隆行指向C中的克隆行。 B不是原始行。

我正在尋找最簡單的方法-最好只是在SQL中。

這是我要執行的操作的一個示例:

在克隆之前:

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

行克隆后:

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

SET FOREIGN_KEY_CHECKS=0然后使用INSERT INTO進行任何操作...選擇以后是否還有其他需要外鍵檢查的操作SET FOREIGN_KEY_CHECKS=1

這是使用子查詢復制表b中的行並使它們指向表a中新的fk的一種方法

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)

但是創建包含源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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM