哪位对oracle熟悉,请教一个问题,
table1和table2结构完全相同。table1 table2
姓名 学号 姓名 学号
001 张三 001
002 李四 002
我想把table2里的姓名更新到table1里面下面能实现吗?update table1set
table1.'姓名'=(select '姓名' from table2)where '学号' in (select '学号' from table2)
table1和table2结构完全相同。table1 table2
姓名 学号 姓名 学号
001 张三 001
002 李四 002
我想把table2里的姓名更新到table1里面下面能实现吗?update table1set
table1.'姓名'=(select '姓名' from table2)where '学号' in (select '学号' from table2)
姓名 学号 姓名 学号
001 张三 001
002 李四 002
set table1.'姓名'=(select '姓名' from table2 where table2.学号=table1.学号)
set table1.'姓名'=(select '姓名' from table2)
where '学号' in (select '学号' from table2)你的有问题,
table1.'姓名'=(select '姓名' from table2)
等号的右边肯定不只是返回一个值,所以会报错。
update table1 set table1.'姓名'=(select '姓名' from table2 where table2.学号=table1.学号)
如果有主键一样还可以使用
update table1,table2 where set table1.姓名=table2.姓名
--这样最全面:
update table1 a set a.姓名=(select 姓名 from table2 b where b.学号=a.学号 and rownum=1)
and exists(select 1 from table2 c where a.学号=c.学号)
update (select a.姓名,b.姓名 from table1 a,table2 b where a.学号=b.学号) set a.姓名=b.姓名
update table1
set
--如果你的字段要用引号的话也是要用双引号,不能用单引号
table1."姓名"=(select "姓名" from table2 where table1."学号"=table2."学号")
where exists(select null from table2 where table1."学号"=table2."学号")
--也可以用merge into 如:
merge into table1 a
using (select 学号,max(姓名) 姓名 from table2 group by 学号) b
on (a.学号=b.学号)
when matched then
update set a.姓名=b.姓名
merge into table1 a
using (select 学号,max(姓名) 姓名 from table2 group by 学号) b
on (a.学号=b.学号)
when matched then
update set a.姓名=b.姓名
---------------
不错。
--------oralce 两表关联的时候没有from的语句,可以使用下面的方法解决,应该没有别的写法了。有的话可以补充
--------如果是sqlserver update table1 a set a.姓名=b.姓名 from table2 b where a.学号=b.学号
SQL> select * from table1;学号 姓名
---------- --------------------
001
002 SQL> select * from table2;学号 姓名
---------- --------------------
001 张三
002 李四
----<1>使用关联查找做
SQL> update table1 a set a.姓名=(select b.姓名 from table2 b where b.学号=a.学号);2 rows updatedSQL> commit;Commit complete
----<2>可以使用视图来做,前提是两个表有关联的主键
SQL> select * from table1;学号 姓名
---------- --------------------
001 张三
002 李四SQL> update (select a.姓名 m,b.姓名 n from table1 a,table2 b where a.学号=b.学号) set m=n;2 rows updatedSQL> commit;Commit completeSQL> select * from table1;学号 姓名
---------- --------------------
001 张三
002 李四SQL> delete from table1;2 rows deletedSQL> insert into table1 values('001',null);1 row insertedSQL> insert into table1 values('002',null);1 row insertedSQL> commit;Commit completeSQL> select * from table1;学号 姓名
---------- --------------------
001
002
-----<3>使用merger into 来做。。
SQL> merge into table1 a
2 using table2 b on (a.学号=b.学号)
3 when matched then
4 update set a.姓名=b.姓名;DoneSQL> commit;Commit completeSQL> select * from table1;学号 姓名
---------- --------------------
001 张三
002 李四SQL>
merge into tb1 using tb2 on(tb1.学号=tb2.学号)
when matched then
update set tb1.姓名=tb2.姓名--or
update set tb1 a set a.姓名=(select b.姓名 from tb2 b where a.学号=b.学号)
where exists(select 1 from tb2 c where a.学号=c.学号)