从Oracle中的另一个表更新表上的密钥

时间:2016-10-14 13:06:40

标签: sql oracle

我试图通过从表(t2)获取值来在键值为(abc)时更新表(t1)上的键。

当我将其限制在某个特定的人时,它正在按预期工作

update table_a t1
   set t1.u_key = (select t2.u_key 
                   from table_b t2 
                   where t2.name_f=t1.name_f 
                     and t2.name_l=t1.name_l 
                     and rownum<=1 
                     and t2='NEVADA')
where t1.u_key = 'abc'
and e.name_f='Lori' 
and e.name_l='U'
;

我最初尝试没有rownum,并且说返回了太多行。

要使用t1.u_key ='abc'运行所有数据并取出特定名称,我尝试了一直运行直到超时。

update table_a t1
   set t1.u_key = (select t2.u_key 
                   from table_b t2 
                   where t2.name_f=t1.name_f 
                     and t2.name_l=t1.name_l 
                     and rownum<=1 
                     and t2='NEVADA')
where t1.u_key = 'abc'
;

请你看看它,并建议我缺少什么。

3 个答案:

答案 0 :(得分:1)

首先应该看一下运行内部SELECT语句时返回的内容:

SELECT t2.u_key FROM table_b t2 
WHERE t2.name_f IN (SELECT name_f FROM table_a WHERE u_key = 'abc') 
AND t2.name_l IN (SELECT name_l FROM table_a WHERE u_key = 'abc') 
AND t2='NEVADA'

检查结果,您会看到返回了多行。

如果每个键只应该有匹配的行,你需要将键添加到内部SELECT中,但是如果没有额外的表描述以及可能来自{{{{}的一些示例条目,我无法告诉你它应该是什么样子的。 1}}和table_a

答案 1 :(得分:0)

使用此:

update     ( 
             SELECT t2.u_key t2key,
                    t1.ukey t1key
              FROM table_b t2,
                   table_a t1
              where t2.name_f=t1.name_f 
              and t2.name_l=t1.name_l                
              and t2='NEVADA'
              and rownum<=1 )
SET     t1key =     t2key
where   t1key = 'abc';   

答案 2 :(得分:0)

merge into table_a t1
 using(
       select name_f, name_l, max(u_key) as new_key
         from table_b t2 
        where t2='NEVADA'
        group by name_f, name_l
      ) t2
   on (t1.name_f=t2.name_f and t1.name_l=t2.name_l and t1.u_key='abc')
 when matched then
  update set t1.u_key=t2.new_key