Home > Enterprise >  How to join one column to two columns in other table
How to join one column to two columns in other table

Time:01-28

I have really tough problem with one select that is bothering me since 11A.M. so what do I mean, I have two tables named Lotnisko and Loty ERD, as shown on the picture.

That's how the tables are looking:

Where Lotnisko means Airport /// Loty means Flights /// NumerLotu is FlightNumber /// MiejsceOdlotu is place of departure /// MiejscePrzylotu is place of arrival

My best select for now is this Tables

select Loty.NumerLotu as [Numer Lotu], Lotnisko.Nazwa as [Miejsce Odlotu]
from Loty
JOIN Lotnisko on Loty.MiejsceOdlotu = Lotnisko.LotniskoID
where NumerLotu = 'KL1995'

select Loty.NumerLotu as [Numer Lotu], Lotnisko.Nazwa as [Miejsce Przylotu]
from Loty
JOIN Lotnisko on Loty.MiejscePrzylotu = Lotnisko.LotniskoID
where NumerLotu = 'KL1995'

Which is giving me this result: Result

What do I want? I want result in one select, best one I've got is this:

select Loty.NumerLotu as [Numer Lotu], Lotnisko.Nazwa as [Miejsce Odlotu], Lotnisko.Nazwa as [Miejsce Przylotu]
from Loty
JOIN Lotnisko on Loty.MiejsceOdlotu = Lotnisko.LotniskoID
JOIN Lotnisko przylot on Loty.MiejscePrzylotu = przylot.LotniskoID
where NumerLotu = 'KL1995'

This is the result: Result2

I want to have this in output:

Numer Lotu Miejsce odlotu Miejsce Przylotu
KL1995 Port lotniczy Amsterdam-Schiphol Port lotniczy Kraków-Balice

CodePudding user response:

Change your query to:

select 
   t1.Numer_Lotu as [Numer Lotu],
   t1.Miejsce_Odlotu as [Miejsce Odlotu],
   t2.Miejsce_Przylotu as [Miejsce Przylotu]
from

  (select Loty.NumerLotu as Numer_Lotu, Lotnisko.Nazwa as Miejsce_Odlotu
  from Loty
  JOIN Lotnisko on Loty.MiejsceOdlotu = Lotnisko.LotniskoID
  where NumerLotu = 'KL1995') t1

join

  (select Loty.NumerLotu as Numer_Lotu, Lotnisko.Nazwa as Miejsce_Przylotu
  from Loty
  JOIN Lotnisko on Loty.MiejscePrzylotu = Lotnisko.LotniskoID
  where NumerLotu = 'KL1995') t2
  
on t1.Numer_Lotu = t2.Numer_Lotu

CodePudding user response:

This is fairly straightforward. Just use the (optional) AS keyword in your joins, and refer to the tables with that in your SELECT.

SELECT
    t1.Numer_Lotu AS "Numer Lotu",
    t1.Miejsce_Odlotu AS "Miejsce Odlotu",
    t2.Miejsce_Przylotu AS "Miejsce Przylotu"
FROM Loty
INNER JOIN Lotnisko AS t1
    ON Loty.MiejsceOdlotu = t1.LotniskoID
INNER JOIN Lotnisko AS t2
    ON Loty.MiejscePrzylotu = t2.LotniskoID
WHERE NumerLotu = 'KL1995'
  •  Tags:  
  • Related