oracle怎么用一个表的多个字段数据更新另一个表相应的字段中

如题所述

第1个回答  2016-09-18
需要更新的表设为表1,数据表为表2,不知道你是要把表2的数据全部更新到表1中还是只更新表1中的部分字段。
可以用merge语句。
merge into 表1 a
using 表2 b
on (表1和表2的关系,例表1id =表2id)
where matched then update
set a.要修改的字段1 = b.要修改的字段1,a.要修改的字段2 = b.要修改的字段2,等等
--这里是将表表一的数据和表2做对比,更新条件是两表的id相同,当满足条件时,执行修改语句,将表1的数据字段改写为表2的
where not matched then insert
values(表2字段1,表2字段2,等等);
--这里是如果不满足条件,执行增加语句,将表2的数据插入到表1中
这里要注意,这两个表中字段名可以不同,但两表的数据类型要相同。
你可以先用别的表试下
第2个回答  2016-09-18
updatet table1
set (name,sex,age)=(select name,sex,age from table2 t2 where t2. id=table1.id)
where exists(select 1 from table2 t3 where table3.id= table1.id)
第3个回答  2017-11-02
假设表a中有多个字段(province ,city)需要从b表获取(两张表的mobile一样),总结了几种写法。
一、updatea set a.province=(select province from b where b.mobile=a.mobile);
updatea set a.city=(select cityfrom b where b.mobile=a.mobile);
这种写法效率太低,尤其是号码有上万条的时候,所以抛弃。
二、update a set a.province=b.province,a.city=b.city from a inner join b on a.mobile=b.mobile.
或者update a set a.province=b.province,a.city=b.city from a,b where a.mobile=b.mobile.
三、update a inner join b on a.mobile=b.mobile set a.province=b.province,a.city=b.city
注意:第二种和第三种写法在oracle行不通的,老是报错,折腾了好长时间,最后还是用下面的语句解决了问题
四、update a set(a.province,a.city)=(select province,city from b where b.mobile=a.mobile)
其实第四种方法是第一种方法的合并。
项目中写的真实例子:
注:用a.city=null不行的本回答被提问者采纳
相似回答