Oracle-兩表關聯更新和插入


需求:

表a(com_name,stock_code,com_sacle,mark,market_location,company_name)

表b(com_name,stock_code,com_sacle)

如果a.stock_code=b.stock_code 把b.com_name,b.com_scale 插入a.com_name,a.com_scale

如果表b.stock_code 在表a中沒有 則把表b(com_name,stock_code,com_sacle)插入表a

 

過程:

--根據tmp_stock表的字段補全stock_collection的字段
update (select a.com_name a1,a.com_scale a2,b.com_name b1,b.com_scale b2
from stock_collection a,tmp_stock b where a.stock_code=b.stock_code)
set a1=b1,a2=b2;

-----------------出現錯誤-----------------------

錯誤報告 -
SQL 錯誤: ORA-01779: 無法修改與非鍵值保存表對應的列
01779. 00000 - "cannot modify a column which maps to a non key-preserved table"
*Cause: An attempt was made to insert or update columns of a join view which
map to a non-key-preserved table.
*Action: Modify the underlying base tables directly.

------解決辦法:設置唯一約束

alter table tmp_stock modify stock_code unique;

----------------------------------------------------

--插入tmp_stock表中有,而stock_collection表中沒有的數據
insert into stock_collection(stock_code,com_name,com_scale)
select stock_code,com_name,com_scale from tmp_stock b 
where b.stock_code not in (select stock_code from stock_collection a);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM