[英]MySql - Create view by merging two tables based on values
我有兩個表:
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 |
我無法找到大小寫或左外部聯接的解決方案。 如何獲得此視圖輸出?
LEFT JOIN financials_standalone
上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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.