用另一个数据更新一个表

表格1:

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

表2:

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

如何运行一个SQL更新查询,可以使用相同的ID更新表1与表2的名称和desc? 所以我得到的最终结果是

表格1:

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

如何做到这一点:

  • SQL Server
  • MySQL的
  • PostgreSQL的
  • 神谕

对于MySql:

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

对于Sql Server:

 UPDATE table1 SET table1.name = table2.name, table1.[desc] = table2.[desc] FROM table1 JOIN table2 ON table1.id = table2.id 

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 

另请参阅Oracle – 使用内部联接更新语句 。

尝试下面的代码。 它正在为我工​​作….

 UPDATE TableOne SET field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id), field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id) WHERE TableOne.id = (SELECT TableTwo.id FROM TableTwo WHERE TableOne.id = TableTwo.id) 
 UPDATE table1 SET `ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`) 

使用以下查询块根据ID更新Table1与Table2:

 UPDATE Table1, Table2 SET Table1.DataColumn= Table2.DataColumn where Table1.ID= Table2.ID; 

这是解决这个问题最简单,最快捷的方法。