ORACLE:使用具有关系的两个表更新查询

Posted

技术标签:

【中文标题】ORACLE:使用具有关系的两个表更新查询【英文标题】:ORACLE : Update query using two table with has relation 【发布时间】:2018-05-21 12:47:41 【问题描述】:

我需要根据在两个表中找到的匹配记录来更新列数据。 我想从 TABLE2 更新 NAME 列的记录

以下是表格

 Table1
---------------
 Id | Name | color
 1  | abc  | red
 2  | def  | green
 3  | ghi  | blue


 Table2
---------------
 Id | Name | color |fiedId
 1  | abc  | red   | 1
 2  | def  | green | 1
 3  | ghi  | blue  | 2

这里table1的ID列是table2中的外键作为fieldId。

所以,我想更新所有符合这种情况的记录

table1.id = table2.fieldId

【问题讨论】:

更新哪个表的记录?并更新什么? 我要更新表 2 中的名称 到目前为止你的尝试是什么? 【参考方案1】:

另一个选项,使用MERGE

merge into table2 t2
using (select id, name from table1) x
on (t2.fieldid = x.id)
when matched then update set
  t2.name = x.name;

或者,将名称设置为“xxx”:

merge into table2 t2
using (select id from table1) x
on (t2.fiedid = x.id)
when matched then update set
  t2.name = 'xxx';

【讨论】:

【参考方案2】:

听起来你只想要这样的更新:

update table2 t2
set    t2.name =
       ( select t1.name
         from   table1 t1
         where  t1.id = t2.fieldid )

关于后续问题:

如果我想为所有匹配的行设置 Name = "xxx" 怎么办?

update table2 t2
set    t2.name = 'xxx'
where  t2.fieldid in
       ( select t1.id from table1 t1 )

或者这可以写成:

update table2 t2
set    t2.name = 'xxx'
where  exists
       ( select null from table1 t1
         where  t1.id = t2.fieldid )

【讨论】:

如果我想为所有匹配的行设置 Name = "xxx" 怎么办?

以上是关于ORACLE:使用具有关系的两个表更新查询的主要内容,如果未能解决你的问题,请参考以下文章

Oracle SQL 更新基于两个表之间的子查询

如何优化查询以使用oracle中另一个表中的列更新表列

如何在oracle中将两个更新查询合并为单个更新查询?

用PLSQL查询oracle数据库中某个表,查询结果如果包含两个字段时就会卡死

访问:具有 2 个主键字段的可更新连接查询,这两个主键字段也是外键

带有内部联接和子查询的 Microsoft Access 更新语句