oracle 多表关联更新语句

来源:互联网 发布:it s high noon 编辑:程序博客网 时间:2024/06/03 15:43

在使用数据库进行更新操作时,我们可能会碰到一种情况,有表a和表b两张表,需要更新表b中的某个字段时,需要关联a b两表,将a表中的字段值赋值给b,此时执行sql语句如下:

update 表a set a.字段1 = (select b.字段1 from 表b where a.字段2=b.字段2) where exists

(select 1 from 表b where a.字段2=b.字段2) 


update 表a set .字段1 = (select b.字段1 from 表b where a.字段2 = b.字段2)  where exists (select 1 from 表b where a.字段2 = b.字段2) 

但是执行语句时发现报了 ORA-01427 单行子查询返回多个行错误 ,观察sql执行发现是由于a.字段2 = b字段2 返回了多条a表中的数据(即对表b的字段2,为某值的数据在表a中有多条记录),此时需要先保证返回的b.字段1 为一条数据 才能执行update语句,可以使用下边的sql

update 表a set 表a.字段1 = (select t.字段1 from (select 表b.字段2,max(字段1)cc from 表b group by 字段2)t where 表a.字段2 = 表b.字段2)  where exists(select 1 from 表b where a.字段2 = b.字段2)

以下是我使用到的一条sql语句

update hotel_member set hotel_member.cityid = ( select t.citity_id from (select aaa.hotelid ,max(cityid) citity_id from hotel_order aaa group by hotelid)t  where hotel_member.hotelid = t.hotelid) where hotel_member.cityid is null


0 0
原创粉丝点击