how to merge two tables to get the last new rows from table 2 and the rest from table 1

流过昼夜 提交于 2020-02-29 04:38:48

问题


i have a problem with joins on two tables into an oracle database, and i can't do that it works. if you see on the image you can two options.

i execute this query:

SELECT f.id_hist, f.producto, f.price
FROM TABLE(fnc_historical('JAP')) f
    inner join new_table g on (f.id_new <> g.id_hist)
union
SELECT f.id_hist, f.producto, g.new_price
FROM TABLE(fnc_historical('JAP')) f
    inner join new_table g on (f.id_new = g.id_hist)

for option/case 1 it works!

but for option/case 2 this query return empty, no rows. and the idea is that must resturn all row from historical information.

Can somebody help me?

Thanks so much.


回答1:


Just use NOT IN to find the records unmatched with new_table g, and gather with the records retrieved by INNER JOIN

SELECT f.id_hist, f.producto, f.price
FROM TABLE(fnc_historical('JAP')) f
WHERE f.id_hist NOT IN
(SELECT DISTINCT f.id_hist
FROM TABLE(fnc_historical('JAP')) f
    inner join new_table g on (f.id_new = g.id_hist)
)
UNION
SELECT f.id_hist, f.producto, g.new_price
FROM TABLE(fnc_historical('JAP')) f
    inner join new_table g on (f.id_new = g.id_hist)



回答2:


I think you are looking for a left join?

SELECT f.id_hist, f.producto,
       COALESCE(g.price, f.price) as price
FROM TABLE(fnc_historical('JAP')) f LEFT JOIN
     new_table g 
     ON f.id_new = g.id_hist;


来源:https://stackoverflow.com/questions/60393804/how-to-merge-two-tables-to-get-the-last-new-rows-from-table-2-and-the-rest-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!