2017-02-15 55 views
0

我有一個數據行,其中多個fk指向同一個表。我怎樣才能產生這樣的:從其指向同一個表的外鍵列中生成多行

表1

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

表2

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

我想產生這樣的

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

我一直在四處尋找,但可能我輸入了錯誤的搜索關鍵字或短語。

感謝

這是我做過什麼

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 

但該表生成帶有空

+0

您正在使用哪些DBMS? Postgres的?甲骨文? –

+0

也請顯示您嘗試的查詢,即使他們不工作 – bouletta

+0

MSSQL.i忘記添加標籤 – CyberNinja

回答

1

使用UNPIVOT行讓每個FK列作爲一個單獨的行。

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

相關問題