表之间的更新

时间:2017-07-24 10:31:36

标签: oracle sql-update

我有两张桌子(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中对于同一名称的剩余记录:

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 :(得分: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和名称,以及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;

答案 1 :(得分: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不为空。