0

我有一个包含多个重复行的父表“策略”,因为有 2 个字段共同构成一个重复项(即 policy_number 和 provider_id)。

我还有一个子表'branch_policy',其中包含重复父行的子记录(还有另一个'policy'子表,但我希望我也可以将相同的解决方案应用于第二个子表)。

在我删除重复的父行之前,我想将重复父记录的子记录重新设置为指向一个父记录,以便安全地删除重复的父记录。

例如:

政策表:

id  policy_number  provider_id  originating_branch
--------------------------------------------------
1   123            1            1
2   123            1            2

分支策略表:

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

分支策略表:

id  policy_id
--------------
1   1
2   1

请注意,选择哪个重复的父记录作为“幸存者”并不重要。

我希望这很清楚!

4

1 回答 1

1

SQL小提琴

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

结果

| 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 |
于 2013-03-21T23:37:13.860 回答