从另一个表中更新一张表的数据。

56

表1:

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

表格 2:

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

我该如何运行一个SQL UPDATE查询,以便使用相同的id更新Table 1和Table 2的名称和描述?因此,最终结果我会得到:

Table 1:

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

如何在以下数据库中实现此操作:

  • SQL Server
  • MySQL
  • PostgreSQL
  • Oracle
5个回答

88

对于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

3
在SQL Server中,我通常使用与您展示的相同的结构化更新。但在这种特殊情况下,FROM部分可能会更简单:只需FROM table2 WHERE table1.id = table2.id,并且可以删除每个赋值左侧的别名。 - Andriy M
1
@andriy-m 我更喜欢将连接谓词放在 JOIN 中而不是 WHERE 中... - The Scrum Meister
1
你能更新Oracle吗?也许可以确认这两个语句哪一个适用于Oracle? - p.campbell
我想补充一下:对于Postgresql,语法略有不同。update a set field1 = concat_ws(' ',field1, table2.middle_name, table2.first_name) from table2 where a.id = table2.fieldX;刚刚添加了一些函数以展示可能性。 - Peter
这是我的问题,谢谢。https://stackoverflow.com/questions/47585429/sql-merge-and-update-statements - user3312649
显示剩余3条评论

27

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 - 使用内部连接更新语句


当匹配时,然后更新设置。看起来你也可以告诉Oracle:“在你那里顺便再点一些薯条”XD。 - Cybermonk

8
UPDATE table1
SET 
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)

7

尝试以下代码。它对我有效...

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) 

这个查询处理速度较慢。 - user3312649

3
使用以下查询块根据ID从Table2更新Table1:
UPDATE Table1, Table2 
SET Table1.DataColumn= Table2.DataColumn
where Table1.ID= Table2.ID;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接