Sql 从指向同一表的外键列生成多行
我有一个数据行,其中多个fk指向同一个表。我如何生成以下内容: 表1Sql 从指向同一表的外键列生成多行,sql,sql-server,Sql,Sql Server,我有一个数据行,其中多个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
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
但此表生成的行为空使用
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
您使用的是哪种数据库管理系统?博士后?Oracle?也请显示您尝试过的查询,即使它们不适用于MSSQL。我忘了添加该标记