使用来自另一个表的数据更新一个表中的行,基于每个表中的一列相等

时间:2011-10-27 15:52:52

标签: sql oracle sql-update

多行 从另一个表中更新为一个表,基于每个表中的一个相等(user_id)。

这两个表都有一个user_id列。当t2列相等时,需要将t1中的数据插入user_id

提前感谢您提供的任何帮助。

5 个答案:

答案 0 :(得分:50)

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      );

或者这个(如果t2.column1< => t1.column1是多对一的,其中任何一个都很好):

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
    and
      rownum = 1    
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      ); 

答案 1 :(得分:25)

如果要使用t2中的数据更新t1中的匹配行,则:

update t1
set (c1, c2, c3) = 
(select c1, c2, c3 from t2
 where t2.user_id = t1.user_id)
where exists
(select * from t2
 where t2.user_id = t1.user_id)

“where exists”部分用于防止在不存在匹配的情况下将t1列更新为null。

答案 2 :(得分:14)

merge into t2 t2 
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
   t2.c1 = t1.c1
,  t2.c2 = t1.c2

答案 3 :(得分:5)

如果记录已存在于t1(user_id匹配)中,则不是插入,除非您乐意创建重复的user_id。

您可能想要更新吗?

UPDATE t1
   SET <t1.col_list> = (SELECT <t2.col_list>
                          FROM t2
                         WHERE t2.user_id = t1.user_id)
 WHERE EXISTS
      (SELECT 1
         FROM t2
        WHERE t1.user_id = t2.user_id);

希望它有所帮助...

答案 4 :(得分:2)

你总是可以使用并省略“当不匹配的部分”

merge into table1 FromTable   
   using table2 ToTable
     on     ( FromTable.field1 = ToTable.field1
          and  FromTable.field2 =ToTable.field2)
when Matched then
update set 
  ToTable.fieldr = FromTable.fieldx,
  ToTable.fields = FromTable.fieldy, 
  ToTable.fieldt =  FromTable.fieldz)
when not matched then
  insert  (ToTable.field1,
       ToTable.field2,
       ToTable.fieldr,
       ToTable.fields,
       ToTable.fieldt)
  values (FromTable.field1,
         FromTable.field2,
         FromTable.fieldx,
         FromTable.fieldy,
         FromTable.fieldz);