Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 832
JcR49 Avatar asked Oct 27 '11 15:10

JcR49


People also ask

How do you UPDATE a column in a table from another column in another table?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.

How do you UPDATE data from one column to another column in SQL?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

How do you UPDATE a table based on conditions?

Update with conditionWHERE clause can be used with SQL UPDATE to add conditions while modifying records. Without using any WHERE clause, the SQL UPDATE command can change all the records for the specific columns of the table.

How can I UPDATE one table column from another table column in SQL Server?

SQL Server UPDATE JOIN syntaxFirst, specify the name of the table (t1) that you want to update in the UPDATE clause. Next, specify the new value for each column of the updated table. Then, again specify the table from which you want to update in the FROM clause.


1 Answers

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       );  
like image 163
Dimitre Radoulov Avatar answered Sep 17 '22 18:09

Dimitre Radoulov