[英]MySql - Create view by merging two tables based on values
I have two tables: 我有两个表:
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 table will have data in addition to the financials_standalone. financials_consolidated表将具有除financials_standalone之外的数据。
Eg: 例如:
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 |
Now I want to combine both the tables as a view :- if the row exists in consolidated then pick that row otherwise pick the row from the financials_standalone table. 现在,我要将两个表合并为一个视图:-如果该行存在于合并中,则选择该行,否则从Financials_standalone表中选择该行。
So the final view output should be like this 所以最终的视图输出应该是这样的
financials_data_view
| fin_id | attr_id | year | value |
---------------------------------------
| fin01 | pe | 2016 | 33.23 |
| fin02 | pe | 2016 | 20.41 |
I am not able to find solution with case-when or left outer join. 我无法找到大小写或左外部联接的解决方案。 How to get this view output?
如何获得此视图输出?
Left join financials_standalone
on financials_consolidated
to get the value from financials_consolidated
in all cases, and use coalesce() function to-return the first non-null value from the 2 tables. LEFT JOIN
financials_standalone
上financials_consolidated
摆脱价值financials_consolidated
在所有情况下,并使用COALESCE()函数,返回从表2的第一个非空值。 Then do a union to get those records from financials_consolidated
to get records from that table that do not exists in the other one. 然后执行一个联合以从
financials_consolidated
获取这些记录,以从该表中获取另一个记录中不存在的记录。 If this cannot be the case, then you do not need the union. 如果不是这种情况,则您不需要联合。
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.