Update rows in one table with data from another table based on one column in each being equal

JcR49 picture JcR49 · Oct 27, 2011 · Viewed 198.8k times · Source

Update many rows into one table from another table based on one column in each being equal (user_id).

both tables have a user_id column. Need to insert data from t2 into t1 when the user_id column are equal.

Thank you in advance for any help offered.

Answer

Dimitre Radoulov picture Dimitre Radoulov · Oct 27, 2011
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
      );

Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):

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
      );