我有一个包含多个重复行的父表'policy',因为有两个字段一起构成一个副本(即policy_number和provider_id)。
我还有一个子表'branch_policy',它包含重复父行的子记录(还有另一个'policy'子表,但我希望我可以将相同的解决方案应用于第二个子表作为孔)。
在删除重复的父行之前,我想将重复父记录的子记录重新父级指向一个父记录,以便安全地删除重复的父记录。
E.g:
政策表:
id policy_number provider_id originating_branch
--------------------------------------------------
1 123 1 1
2 123 1 2
branch_policy表:
id policy_id
--------------
1 1
2 2
我希望将branch_policy的第二条记录设置为policy_id = 1,然后删除ID为2的策略记录,以便以
结尾政策表:
id policy_number provider_id originating_branch
--------------------------------------------------
1 123 1 1
branch_policy表:
id policy_id
--------------
1 1
2 1
请注意,选择哪个重复的父记录作为“幸存者”并不重要。
我希望这很清楚!
答案 0 :(得分:0)
MySQL 5.5.30架构设置:
create table policy (
id int not null,
policy_number varchar(100) not null,
provider_id int not null,
originating_branch int not null
);
create table branch_policy(id int, policy_id int);
insert policy (id, policy_number, provider_id, originating_branch)
values
(1, '123', 1, 1),
(2, '123', 1, 2),
(3, '1234', 3, 3),
(4, '1234', 3, 4)
;
insert branch_policy(id, policy_id) values
(1, 1), (2, 2), (3, 2),
(4, 3), (5, 3), (6, 4)
;
update branch_policy bp
join (select
po.id as old_id,
pn.new_id
from policy po
join (
select
policy_number,
provider_id,
min(id) as new_id
from policy
group by policy_number, provider_id) as pn
on po.policy_number = pn.policy_number
and po.provider_id = pn.provider_id) as p
on bp.policy_id = p.old_id
set bp.policy_id = p.new_id
;
delete po
from policy po
join (
select
policy_number,
provider_id,
min(id) as new_id
from policy
group by policy_number, provider_id) as pn
on po.policy_number = pn.policy_number
and po.provider_id = pn.provider_id
where po.id <> pn.new_id
查询1 :
select * from policy
<强> Results 强>:
| ID | POLICY_NUMBER | PROVIDER_ID | ORIGINATING_BRANCH |
---------------------------------------------------------
| 1 | 123 | 1 | 1 |
| 3 | 1234 | 3 | 3 |
查询2 :
select * from branch_policy
结果2 :
| ID | POLICY_ID |
------------------
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 3 |
| 5 | 3 |
| 6 | 3 |