0

I have a table with 3 columns in my table Travel (and of course some more):

AirportFrom, AirportTo, AirportFound.

The columns above display ID's from airports. In the table Airports are 2 columns AirportID and AirportName. Instead of displaying the ID's from the airports I want to display the AirportNames.

But when I use:

SELECT id
     , AirportFrom
     , Airports.Airportname
     , AirportTo
     , Airports.Airportname
     , AirportFound
     , Airports.Airportname 
  FROM Travel 
  LEFT 
  JOIN Airports 
    ON AirportTo = Airports.AirportID
-- LEFT JOIN Airports ON AirportFrom = Airports.AirportID
-- LEFT JOIN Airports ON AirportFound = Airports.AirportID

It only displays the airport name of the first join in every column. I want to show the airport name for each of the 3 joins

2 Answers 2

3

Provide multiple aliases for joined table each time you left join, and join them as you have multiple tables:

SELECT 
    Travel.id, 
    airport_to.Airportname as to_name, 
    airport_from.Airportname as from_name, 
    airport_found.Airportname as found_name, 
FROM Travel 
LEFT JOIN Airports airport_to ON Travel.AirportTo = airport_to.AirportID
LEFT JOIN Airports airport_from ON Travel.AirportFrom = airport_from.AirportID
LEFT JOIN Airports airport_found ON Travel.AirportFound = airport_found.AirportID

EDIT: Replace reserved words in table aliases. Thanks for the reminder!

Sign up to request clarification or add additional context in comments.

2 Comments

up vote. better readability and understandability vis-a-vis other answer
watch out for reserved words
1

Your query needs table aliases (for multiple joins to the same table). Then, be sure to use qualified columns names for all columns in a query. This helps you write correct queries and it helps you and other people understand what is going on. So:

SELECT t.id, t.AirportFrom, apt.Airportname,
       t.AirportTo, apf.Airportname,
       t.AirportFound, apfo.Airportname 
FROM Travel t LEFT JOIN
     Airports apt
     ON t.AirportTo = apt.AirportID LEFT JOIN
     Airports apf
     ON t.AirportFrom = apf.AirportID LEFT JOIN
     Airports apfo
     ON t.AirportFound = apfo.AirportID;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.