简体   繁体   中英

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.

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.

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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM