SQL查询连接到同一个父表两次

时间:2018-05-10 18:09:16

标签: sql sql-server tsql

我的数据库中有两个表:

表 航班:

ID
ID_Destination
ID_Source

表格位置:

ID (that relatesto the id of source and destination)
Name
Country
Etc..

现在我需要一个查询,它会向我提供从某个来源到特定目的地的所有航班的信息。我在查询编辑器中尝试了很长时间,但内部联接在这里不起作用。我该怎么用?

我需要的结果如下:

1st flight: Naples Italy |London England
2nd flight: Rome Italy | Mailand Italy
etc..

3 个答案:

答案 0 :(得分:1)

下一个内部联接应该在这里工作:

SELECT f.ID, CONCAT(sl.Name, ' ', sl.Country), CONCAT(dl.Name, ' ', dl.Country)
FROM Flights as f
INNER JOIN Locations as sl ON sl.ID = f.ID_Source
INNER JOIN Locations as dl ON dl.ID = f.ID_Destination

函数“CONCAT”是MySql的一部分,因此如果没有它,这个函数不适用于所有数据库:

SELECT f.ID, sl.Name, sl.Country, dl.Name, dl.Country
FROM Flights as f
INNER JOIN Locations as sl ON sl.ID = f.ID_Source
INNER JOIN Locations as dl ON dl.ID = f.ID_Destination

答案 1 :(得分:0)

您可以两次加入位置表:

SELECT 
   id, 
   source.name as `Source Name`, 
   source.country as `Source Country`, 
   destination.name as `Destination Name`, 
   destination.country as `Destination Country` 
FROM flights
JOIN locations source ON source.id = flights.source_id
JOIN locations destination ON destination.id = flights.destination_id

答案 2 :(得分:0)

您还可以使用subquery

select id,
      (select top(1) concat(name, ' ', country) from locations where id = f.ID_Source) as Source,
      (select top(1) concat(name, ' ', country) from locations where id = f.ID_Destination) as Destination, 
from flights f
group by id;