2016-10-31 15 views
0

に基づいて2つのテーブルをマージしてビューを作成します。MySQLは、私は2つのテーブルを持っている値

例:

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 | 

ようにする必要があります。このビュー出力を取得するには?

答えて

1

financials_consolidatedの値を得るには、すべてfinancials_consolidatedの値を得るために左へfinancials_standaloneを結合し、coalesce()関数を使用して2つのテーブルから最初の非NULL値を返します。次に、これらのレコードを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 
+0

ありがとうございます。提案されたクエリが機能しています。 –

関連する問題