2017-02-15 10 views
0

私は同じテーブルを指し示す複数のfkを持つデータ行を持っています。私はこれを生成することができます方法:は、同じテーブルを指すその外部キー列から複数の行を生成します

表1

id | name | fk1 | fk2 | fk3 
1 test EA US NULL 
2 test2 Null UK US 

表2

私は私の周りおそらく見てきたこの

id | name | details 
1 test East Asia 
1 test United States 
2 test2 United Kingdom 
2 test2 United States 

のようなものを生成したい

id | details 
EA East Asia 
US United States 
UK United Kingdom 

間違った検索キーワードやフレーズを入力しています。

おかげ

は、これは私が

select t1.id,t1.name,t2.details from table1 t1 
left join table2 t2 on t2.id = t1.fk1 
union 
(select t1.id,t1.name,t2.details from table1 t1 
left join table2 t2 on t2.id = t1.fk2 
) 
union 
select t1.id,t1.name,t2.details from table1 t1 
left join table2 t2 on t2.id = t1.fk3 

やったことですが、この表では、個別の行としてあなたのFKの列のそれぞれを取得するには、ヌル

+0

どのDBMSを使用していますか? Postgres?オラクル? –

+0

また、動作しなくても試した質問を表示してください。 – bouletta

+0

MSSQL.iがそのタグを追加するのを忘れた – CyberNinja

答えて

1

使用UNPIVOTで行を生成します。

select u.id, u.name, t2.details 
from table1 t1 
unpivot(
    region for regions in (fk1, fk2, fk3) 
) u 
join table2 t2 on t2.id = u.region 
+0

ありがとうございます。これは完璧です!!!初めてピボットを使用する。 – CyberNinja

関連する問題