2013-01-17 109 views
5

Trips加入两个表的多个外键

TripId_PK 
StartLocationId_FK 
EndLocationId_FK 

Locations

LocationId_PK 
Name 

我如何加入两个表的两倍,这样我可以得到这样一个数据集:

TripId_PK 
StartLocationName 
EndLocationName 

在此先感谢。

回答

6
SELECT t.TripId_PK, ls.name StartLocationName, le.name EndLocationName 
FROM trips t 
JOIN locations ls 
ON  ls.LocationId_PK = t.StartLocationId_FK 
JOIN locations le 
ON  le.LocationId_PK = t.EndLocationId_FK 
2

你可以试试这个

SELECT t.TripId_PK, ls.StartLocationName, le.EndLocationName 
FROM Trips t 
JOIN Locations ls ON t.StartLocationId_FK = ls.LocationId_PK 
JOIN Locations le ON t.EndLocationId_FK = le.LocationId_PK