获取具有相同表的两个外键的表的结果

时间:2013-10-25 11:37:51

标签: sql-server-2008-r2

我有两个表假设表'friendship'与列f1,f2和'people'与列p_id,p_name。

firendship:=>

f1    f2
--------
01    10
02    11
03    12

人:=>

p_id  p_name
------------
01    Vijay
02    Ajay
03    Gaurav
10    Sunny
11    Amit
12    Sandeep

我想要像这张表那样的结果

结果表应为:=>

f1  f1_name  f2  f2_name
------------------------
01  Vijay    10   Sunny
02  Ajay     11   Amit
03  Gaurav   12   Sandeep

我尝试使用Union两个表但无法找到准确的结果

3 个答案:

答案 0 :(得分:2)

SELECT a.p_id f1, a.p_name f1_name, b.p_id f2, b.p_name f2_name FROM People a JOIN friendship f ON (f.f1 = a.p_id) JOIN People b ON (f.f2 = b.p_id)

答案 1 :(得分:0)

我认为这可以解决您的问题。

select a.f1, c.p_name, b.f2, c.p_name
(select * from tablea) as a,// which have f1 and f2 columns
(select * from tablea) as b,
(select * from people) as c 
where a.f1=c.p_id and b.f2=c.p_id

答案 2 :(得分:0)

您需要加入此

select f1,  p.p_name as f1_name , f2, p1.p_name f2_name
from firendship as f
inner join People as p on f.f1=p.p_id
inner join People as p1 on f.f2=p1.p_id