MySql - 通过根据值合并两个表来创建视图

MySql - Create view by merging two tables based on values

我有两个 table:

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 除了 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 |

现在我想将两个 table 合并为一个视图:- 如果该行存在于合并中,则选择该行,否则从 financials_standalone table 中选择该行。

所以最终的视图输出应该是这样的

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

我找不到 case-when 或左外连接的解决方案。如何获得这个视图输出?

Left join financials_standalone on financials_consolidated 以在所有情况下从 financials_consolidated 获取值,并使用 coalesce() 函数 -return 第一个非空值来自 2 table 的值。然后做一个联合从 financials_consolidated 中获取那些记录,从 table 中获取另一个不存在的记录。如果不是这种情况,那么您不需要联合。

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