MySql - 通过基于值合并两个表来创建视图

时间:2016-10-31 10:24:13

标签: mysql database database-view

我有两张桌子:

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 |

我无法通过case-when或left outer join找到解决方案。如何获得此视图输出?

1 个答案:

答案 0 :(得分:1)

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