Come si usa un LEFT JOIN due volte sulla stessa colonna con MySQL?
Domanda
Ho due tabelle, una per gli aeroporti e uno per le rotte.
Aeroporti sembra un po 'come questo
Airports
-------------------------------------
id | code | name |
-------------------------------------
01 | LGW | London Gatwick |
-------------------------------------
02 | LHR | London Gatwick |
e così via ....
e un altro per le rotte come questo
Routes
---------------------------
id | ORIGIN | DESTINATION |
---------------------------
01 | LGW | VCE |
---------------------------
02 | TSF | LHR |
e così via ...
Ho bisogno di selezionare rotte da tavolo, ma voglio anche per ottenere i nomi aeroporto. Il po 'di confusione è che ho bisogno di interrogare il codice aeroporto due volte. Sto cercando qualcosa di simile
SELECT routes.*, airports.name as origin_name FROM routes
LEFT JOIN airports ON airports.IATA = routes.origin
LEFT JOIN airports ON airports.IATA = routes.destination
WHERE origin = 'LHR' AND destination = 'VCE' OR origin = 'VCE'
Il che si può o non può sapere, non funziona. Come potrei fare per fare questo?
Soluzione
Utilizzare alias:
SELECT
routes.*,
a1.name AS origin_name,
a2.name AS destination_name
FROM routes r
LEFT JOIN airports a1 ON a1.IATA = r.origin
LEFT JOIN airports a2 ON a1.IATA = r.destination
WHERE
r.origin = 'LHR' AND r.destination = 'VCE' OR r.origin = 'VCE'
Altri suggerimenti
Basta dare tavolo due alias diversi. Qualcosa di simile (non testato);
SELECT routes.*, o.name as origin, d.name as destination FROM routes
LEFT JOIN airports o ON o.IATA = routes.origin
LEFT JOIN airports d ON d.IATA = routes.destination
WHERE origin = 'LHR' AND destination = 'VCE' OR origin = 'VCE'
È necessario aggiungere la tabella AEROPORTI due volte utilizzando alias ....
SELECT ORIGIN_AIRPORT.NAME,
DESTINATION_AIRPORT.NAME
FROM AIRPORTS ORIGIN_AIRPORT,
AIRPORTS DESTINATION_AIRPORT,
ROUTES
WHERE ROUTES.ORIGIN = ORIGIN_AIRPORT.CODE
AND ROUTES.DESTINATION = DESTINATION_AIRPORT.CODE;
Mettere un alias sui nomi di tabella:
SELECT routes.*, a1.name as origin_name FROM routes
LEFT JOIN airports AS a1 ON a1.IATA = routes.origin
LEFT JOIN airports AS a2 ON a2.IATA = routes.destination
WHERE origin = 'LHR' AND destination = 'VCE' OR origin = 'VCE'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow