我有一张表有2张来自同一张表的外键
UserID Name
1 Alpha
2 Bravo
3 Charlie
4 Delta
5 Foxtrot
Record UserID UserID2
1 1 5
2 3
3 4
是否可以将它们显示为多行?
Record Name
1 Alpha
1 Foxtrot
2 Charlie
3 Delta
我尝试使用INNER JOIN / JOIN但只能使用一个外键(UserID)。
答案 0 :(得分:3)
您可以使用两个联接,在这种情况下left join
将值放在一行:
select t1.record, t2a.name, t2b.name
from t1 left join
t2 t2a
on t2a.userid = t1.userid left join
t2 t2b
on t2b.userid = t1.userid2;
对于单独的行,请使用union all
:
select t1.record, t2.name
from t1 join
t2
on t2.userid = t1.userid
union all
select t1.record, t2.name
from t1 join
t2
on t2.userid = t1.userid2
order by record;
答案 1 :(得分:3)
更简单的方法:
Select t2.record AS Record,Name
From t1 inner join t2
on t1.userId = t2.UserID or t1.userId = t2.userid2