How to do an INNER JOIN on multiple columns

前端 未结 5 2050
春和景丽
春和景丽 2020-11-30 16:57

I\'m working on a homework project and I\'m supposed to perform a database query which finds flights either by the city name or the airport code, but the flights

相关标签:
5条回答
  • 2020-11-30 17:26

    Why can't it just use AND in the ON clause? For example:

    SELECT *
    FROM flights
    INNER JOIN airports
       ON ((airports.code = flights.fairport)
           AND (airports.code = flights.tairport))
    
    0 讨论(0)
  • 2020-11-30 17:28

    if mysql is okay for you:

    SELECT flights.*, 
           fromairports.city as fromCity, 
           toairports.city as toCity
    FROM flights
    LEFT JOIN (airports as fromairports, airports as toairports)
    ON (fromairports.code=flights.fairport AND toairports.code=flights.tairport )
    WHERE flights.fairport = '?' OR fromairports.city = '?'
    

    edit: added example to filter the output for code or city

    0 讨论(0)
  • 2020-11-30 17:33

    something like....

    SELECT f.*
          ,a1.city as from
          ,a2.city as to
    FROM flights f
    INNER JOIN airports a1
    ON f.fairport = a1. code
    INNER JOIN airports a2
    ON f.tairport = a2. code
    
    0 讨论(0)
  • 2020-11-30 17:37

    You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:

    SELECT 
        airline, flt_no, fairport, tairport, depart, arrive, fare
    FROM 
        flights
    INNER JOIN 
        airports from_port ON (from_port.code = flights.fairport)
    INNER JOIN
        airports to_port ON (to_port.code = flights.tairport)
    WHERE 
        from_port.code = '?' OR to_port.code = '?' OR airports.city='?'
    

    Note that the to_port and from_port are aliases for the first and second copies of the airports table.

    0 讨论(0)
  • 2020-11-30 17:40

    If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:

    SELECT
       Flights.*,fromAirports.*,toAirports.*
    FROM
       Flights
    INNER JOIN 
       Airports fromAirports on Flights.fairport = fromAirports.code
    INNER JOIN 
       Airports toAirports on Flights.tairport = toAirports.code
    WHERE
     ...
    
    0 讨论(0)
提交回复
热议问题