Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two tables with multiple foreign keys

Tags:

sql

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.

like image 432
Blaise Avatar asked Jan 17 '13 22:01

Blaise


People also ask

Is it possible to link two tables using two foreign keys?

If there is exactly one foreign key with the same name as a table in the join, SQL Anywhere uses it to generate the join condition. If there is more than one foreign key with the same name as a table, the join is ambiguous and an error is issued.

Can you have multiple same foreign keys?

(a) is fine: you can have as many entities as you want referencing the same foreign key.

Do foreign keys improve join performance?

Foreign key indexes can significantly improve performance for queries that involve joins between the parent and child tables.


2 Answers

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
like image 151
Quassnoi Avatar answered Oct 13 '22 10:10

Quassnoi


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
like image 27
bobs Avatar answered Oct 13 '22 10:10

bobs