2016-10-31 39 views
0

合併兩個表我有兩個表:MySQL的 - 創建視圖,基於價值觀

financials_standalone ('fin_id', 'attr_id', 'year', 'value'); 
financials_consolidated ('fin_id', 'attr_id', 'year', 'value'); 

('fin_id', 'attr_id', 'year') is the unique key 

financials_consolidated表將在除financials_standalone數據。

如:

financials_standalone 
| fin_id | attr_id | year | value | 
--------------------------------------- 
| fin01 | pe  | 2016 | 33.23 | 
| fin02 | pe  | 2016 | 12.52 | 

financials_consolidated 
| fin_id | attr_id | year | value | 
--------------------------------------- 
| fin02 | pe  | 2016 | 20.41 | 

現在,我想這兩個表的視圖結合起來: - 如果存在合併的行然後選擇該行從financials_standalone表,否則挑行。

所以最終視圖輸出應該是這樣的

financials_data_view 
| fin_id | attr_id | year | value | 
--------------------------------------- 
| fin01 | pe  | 2016 | 33.23 | 
| fin02 | pe  | 2016 | 20.41 | 

我無法找到的情況下,時或左外連接解決方​​案。如何獲得這個視圖輸出?

回答

1

左連接financials_standalone on financials_consolidated在所有情況下從financials_consolidated獲得值,並使用coalesce()函數返回2個表中的第一個非空值。然後做一個工會,從financials_consolidated那裏得到那些記錄,從那張表中得到另一個不存在的記錄。如果情況不是這樣,那麼你不需要工會。

select fs.fin_id, fs.attr_id, fs.year, coalesce(fc.value, fs.value) as val 
from `financials_standalone` fs 
left join `financials_consolidated` fc 
    on fs.fin_id=fc.fin_id 
    and fs.attr_id=fc.attr_id 
    and fs.year=fc.year 
union 
select fc.fin_id, fc.attr_id, fc.year, fc.value 
from `financials_consolidated` fc 
left join `financials_standalone` fs 
    on fs.fin_id=fc.fin_id 
    and fs.attr_id=fc.attr_id 
    and fs.year=fc.year 
where fs.fin_id is null 
+0

謝謝陰影。建議的查詢正在運行。 –