Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update one table with data from another

Tags:

sql

database

Table 1:

id    name    desc ----------------------- 1     a       abc 2     b       def 3     c       adf 

Table 2:

id    name    desc ----------------------- 1     x       123 2     y       345 

How do I run an sql update query that can update Table 1 with Table 2's name and desc using the same id? So the end result I would get is

Table 1:

id    name    desc ----------------------- 1     x       123 2     y       345 3     c       adf 

How can this be done for:

  • SQL Server
  • MySQL
  • PostgreSQL
  • Oracle
like image 891
Patrick Avatar asked Feb 18 '11 01:02

Patrick


People also ask

How do you update a table with data from another table in SQL?

UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID. we can use the following command to create a database called geeks.


2 Answers

For MySql:

UPDATE table1 JOIN table2      ON table1.id = table2.id SET table1.name = table2.name,     table1.`desc` = table2.`desc` 

For Sql Server:

UPDATE   table1 SET table1.name = table2.name,     table1.[desc] = table2.[desc] FROM table1 JOIN table2     ON table1.id = table2.id 
like image 144
The Scrum Meister Avatar answered Oct 05 '22 06:10

The Scrum Meister


Oracle 11g R2:

create table table1 (   id number,   name varchar2(10),   desc_ varchar2(10) );  create table table2 (   id number,   name varchar2(10),   desc_ varchar2(10) );  insert into table1 values(1, 'a', 'abc'); insert into table1 values(2, 'b', 'def'); insert into table1 values(3, 'c', 'ghi');  insert into table2 values(1, 'x', '123'); insert into table2 values(2, 'y', '456');  merge into table1 t1 using (select * from table2) t2 on (t1.id = t2.id) when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;  select * from table1;          ID NAME       DESC_ ---------- ---------- ----------          1 x          123          2 y          456          3 c          ghi 

See also Oracle - Update statement with inner join.

like image 35
user272735 Avatar answered Oct 05 '22 06:10

user272735