根据另一个表和3个密钥中的数据更新Oracle中的表

时间:2017-01-08 20:25:52

标签: sql oracle

所有

这是我的两张桌子:

表客户

First_Name | Last_Name | Purchases| Age
  John        Rambo         10       55
  George      Washington    17       99
  Eli         Manning       7        35

表客户端

First_Name | Last_Name | Purchases| Client_Id | Date_Added
  John        Rambo         10       4          12-mar-2016
  George      Washington    17       6          20-jan-2016
  Eli         Manning       7        3          10-dec-2016
  Jerry       Seinfeld      4        3          19-mar-2016

期望的结果

表客户:

    First_Name | Last_Name | Purchases| Age | Client_Id | Date_Added
     John        Rambo         10       55      4          12-mar-2016
     George      Washington    17       99      6          20-jan-2016
     Eli         Manning       7        35      3          10-dec-2016

我想将Client_Id和Date_Added添加到客户。可以说我添加了这些列,现在必须设计更新语句。条件是,如果First_Name或Last_Name或Purchases在两个表中都匹配,则填充customer。让我们只是为了论证这些字段永远是唯一的,所以我们只需要一个匹配。你会怎么在oracle中这样做?请注意,这将为几十万条记录完成。

1 个答案:

答案 0 :(得分:1)

根据您的所有假设,说您已添加了所需的列,您可能需要MERGE

<强>设置:

create table sustomer(First_Name , Last_Name , Purchases, Age) as (
 select 'John'   , 'Rambo'      , 10 , 55 from dual union all
 select 'George' , 'Washington' , 17 , 99 from dual union all
 select 'Eli'    , 'Manning'    ,  7 , 35 from dual
);
create Table client(First_Name , Last_Name ,Purchases,Client_Id ,Date_Added) as (
 select 'John'   ,'Rambo'      , 10 , 4 , to_date('12-03-2016','dd-mm-yyyy') from dual union all
 select 'George' ,'Washington' , 17 , 6 , to_date('20-01-2016','dd-mm-yyyy') from dual union all
 select 'Eli'    ,'Manning'    ,  7 , 3 , to_date('10-12-2016','dd-mm-yyyy') from dual union all
 select 'Jerry'  ,'Seinfeld'   ,  4 , 3 , to_date('19-03-2016','dd-mm-yyyy') from dual 
);
alter table customer add Date_Added date;
alter table customer add Client_Id number;

<强> MERGE:

merge into customer cu
using ( select * from client) cl
on ( cl.First_Name = cu.First_Name OR
     cl.Last_Name  = cu.Last_Name  OR
     cl.Purchases  = cu.Purchases
   )
when matched then
    update set Date_Added = cl.Date_Added,
               Client_Id  = cl.Client_Id

这给出了您的数据:

FIRST_ LAST_NAME   PURCHASES        AGE  CLIENT_ID DATE_ADDE
------ ---------- ---------- ---------- ---------- ---------
John   Rambo              10         55          4 12-MAR-16
George Washington         17         99          6 20-GEN-16
Eli    Manning             7         35          3 10-DEC-16