我在表 A 中有一组行(带有 AI PK),我想根据特定条件克隆这些行,即:
INSERT INTO A (field1, field2, field3) SELECT field1,field2,field3 FROM A WHERE (criteria)
但是,这些行与表 B 具有 1-1 关系,表 B 在 B 中有一个 AI PK,在 A 中有一个 FK。我还想克隆表 B 中的相关行,并将 A 中的克隆行指向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
最佳答案
这是一种使用子查询复制表 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)
关于MySQL:克隆表 A 中的多行和表 B 中的相关行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33642015/