簡體   English   中英

從 Oracle 中的另一個表更新表上的鍵

[英]Updating a key on table from another table in Oracle

當鍵值為 (abc) 時,我試圖通過從表 (t2) 獲取值來更新表 (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'
;

你能看看它並建議我錯過什么嗎?

您應該首先查看單獨運行內部 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 中,但我無法告訴您如果沒有額外的表描述以及可能來自table_atable_b一些示例條目,它應該是什么樣子。

用這個:

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';   
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM