2016-11-16 5 views
1

それぞれに異なる列を含み、すべての製品の異なるサブセットを含むいくつかの表があります。 すべての製品に関するすべての情報のリストを取得したいので、product_idfull outer joinを追加します。複数の列のいずれかで結合する

私は

select * from table1 
full outer join table2 b on b.product_id = table1.product_id 
... 
full outer join tableN c on b.product_id = table1.product_id 

を試してみましたが、これはproduct_idがTABLE1に存在しない複数の行になりますが、表2およびtableNに存在する可能性があります。 結合列を「結合」する方法はありますか?あなたは以上の2つのテーブルをfull outer joinを使用する場合は

+1

互換性のないデータベースタグを削除しました。実際に使用しているデータベースにタグを付けてください。 –

+0

また、テーブルエイリアスcへの結合がc.product_idでフィルタリングされていませんb.product_idでフィルタリングされています – Hogan

答えて

2

、あなたはこのようなものになってしまいます: - Postgresではでサポートされてではなく、SQL Serverの -

select * 
from table1 a full outer join 
    table2 b 
    on b.product_id = a.product_id 
    ... full outer join 
    tableN c 
    on c.product_id = coalesce(b.product_id, a.product_id) 

using句これを簡素化。列の名前はすべて同じであると仮定します。

代わりに、運転台があります。あなたは便利なすべての製品のテーブルを持っていない場合は、作成することができます

select * 
from (select product_id from table1 union 
     select product_id from table2 union 
     . . . 
     select product_id from tableN 
    ) driving left join 
    table1 a 
    on a.product_id = driving.product_id left join 
    table2 b 
    on b.product_id = driving.product_id 
    ... full outer join 
    tableN c 
    on c.product_id = driving.product_id; 

これは解釈が容易であるべきとon句は、簡略化されています。

最後に、共通の列が必要な場合があります。もしそうなら、単にunion allを使用します。

select product_id, col1, col2, col3 from table1 union all 
select product_id, col1, col2, col3 from table2 union all 
     . . . 
select product_id, col1, col2, col3 from tableN; 

これはNULL値を持つ列の増殖を防ぐことができます。

0
select * from table1 
inner join 
(
SELECT * FROM table2 
UNION ALL 
SELECT * FROM table3 
UNION ALL ........ 
SELECT * FROM tableN 
) N 
on N.product_id = table1.product_id 
関連する問題