Blaise
Blaise

Reputation: 22202

Join two tables with multiple foreign keys

Table Trips

TripId_PK
StartLocationId_FK
EndLocationId_FK

Table Locations

LocationId_PK
Name

How can I join the two table twice so that I can get a dataset like:

TripId_PK
StartLocationName
EndLocationName

Thanks in advance.

Upvotes: 7

Views: 17547

Answers (2)

bobs
bobs

Reputation: 22184

You can try this

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

Upvotes: 3

Quassnoi
Quassnoi

Reputation: 425251

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

Upvotes: 8

Related Questions