首页 文章

表之间的更新

提问于
浏览
0

我有两个表(ORACLE11):

TABLE1: (ID_T1 is TABLE1 primary key)
| ID_T1 | NAME  | DATEBEGIN  | DATEEND    |
| 10    | test  | 01/01/2017 | 01/06/2017 |
| 11    | test  | 01/01/2017 | null       |
| 12    | test1 | 01/01/2017 | 01/06/2017 |
| 13    | test1 | 01/01/2017 | null       |
TABLE2: (ID_T2 is TABLE2 primary key and ID_T1 is TABLE2 foreign key on TABLE1)
| ID_T2 | ID_T1 |
| 1     | 10    |
| 2     | 11    |
| 3     | 11    |
| 4     | 12    |
| 5     | 13    |

我需要删除TABLE1中TABLE1.DATEEND ='null'的所有行

但首先我必须更新TABLE2以将TABLE2.ID_T1修改为TABLE1中的相同NAME的剩余记录:

TABLE2:
| ID_T2 | ID_T1 |
| 1     | 10    |
| 2     | 10    |
| 3     | 10    |
| 4     | 12    |
| 5     | 12    |

我试过这个:

UPDATE TABLE2 
SET TABLE2.ID_T1 = (
    SELECT TABLE1.ID_T1 
    FROM TABLE1 
    WHERE TABLE1.DATEBEGIN = '01/01/2017' 
    AND TABLE1.DATEEND IS NOT NULL
    )
WHERE TABLE2.ID_T1 = (
    SELECT TABLE1.ID_T1 
    FROM TABLE1 
    WHERE TABLE1.DATEBEGIN = '01/01/2017' 
    AND TABLE1.DATEEND IS NULL
    );

但我不知道如何加入TABLE1.NAME并为TABLE2的所有行执行此操作 . 在此先感谢您的帮助 .

2 回答

  • 0

    首先创建一个临时表,找出要为哪个名称保留的id . 在多个可能值的情况下,我通过升序或id_t1选择了一个 .

    create table table_2_update as 
    select id_t1, name from (select id_t1, name row_number() over(partition by 
    name order by id_t1) from table1 where name is not null) where rn=1;
    

    创建下一个表以了解table2的哪个id连接到table1的哪个名称 .

    create table which_to_what as 
    select t2.id_t2, t2.id_t1, t1.name from table1 t1 inner join table2 t2 on 
    t1.id_t1 = t2.id_t2 group by t2.id_t2, t2.id_t1, t1.name;
    

    由于这个新创建的表现在包含table1的id和name,以及table2的id,因此合并到它中以保留一对一的id1和table1的名称 .

    merge into which_to_what a
    using table_2_update b
    on (a.name=b.name)
    when matched then update set 
    a.id_t1=b.id_t1;
    

    现在最后我们有一个包含最终正确值的表,您可以将此故事重命名为table2,或者根据新表和原始table2的id合并原始table2 .

    merge into table2 a
    using which_to_what a
    on (a.id_t2=b.id_t2)
    when matched then update set
    a.id_t1=b.id_t1;
    

    最后从table1中删除空值 .

    delete from table1 where dateend is null;
    
  • 0

    您可以通过将 table1 加入到自身来加入 name 列来完成此操作 . 使用第一个表(a)链接到 table2.id_t1 和第二个表(b)以获取 t1_id ,其中 dateend 不为空 .

    UPDATE table2
    SET table2.id_t1 = (
        select b.id_t1
        from   table1 a, table1 b
        where  a.name = b.name
        and    b.dateend is not null
        and    a.id_t1 = table2.id_t1
    )
    WHERE EXISTS (
        select b.id_t1
        from   table1 a, table1 b
        where  a.name = b.name
        and    b.dateend is not null
        and    a.id_t1 = table2.id_t1
    );
    

    这假设只有一个 table1 记录,其中 dateend 不为空 .

相关问题