简体   繁体   中英

SQL Multiple columns same join column

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

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM