SQL无法获得准确的数据

时间:2017-11-21 06:28:07

标签: sql sql-server vb.net erd

在SQL中获取数据时遇到麻烦。如何有一个表源或主键但有两个不同的外键。

This is the ERD This is the result but when i put the Departure it will be vice versa

3 个答案:

答案 0 :(得分:1)

如果我能正确理解您的问题,那么您似乎正试图同时接受"离开"和"到达"来自同一连接的值。为了实现这一目标,您需要为路由到机场(以及相应的别名)有两个单独的连接,用于每个"离开"和#34;到达"。

select date, 
    time, 
    ArrivalAirport.IATACode as Departure,
    DepartureAirport.IATACode as Arrival,
    FlightNumber,
    Aircrafts.Name,
    EconomyPrice,
    Schedules.ID
from Schedules
inner join [Routes] on Schedules.RouteID = [Routes].ID
inner join Aircrafts on Schedules.AircraftID = Aircrafts.ID
inner join Airports as ArrivalAirport on ArrivalAirport.ID = [Routes].ArrivalAirportID
inner join Airports as DepartureAirport on DepartureAirport.ID = [Routes].DepartureAirportID

请注意"机场"的两个实例。连接需要相应的别名,以便您可以在选择投影中执行所需的操作。

答案 1 :(得分:0)

您需要为使用两次的表使用表别名,然后再连接两次。

SELECT Routes.ID, DEP.IATACode, ARR.IATACode
FROM dbo.Routes
INNER JOIN dbo.Airports AS DEP ON DEP.ID = Routes.DepartureAirportID
INNER JOIN dbo.Airports AS ARR ON ARR.ID = Routes.ArrivalAirportID

一旦定义,您就可以在查询中的任何位置使用别名。见here for more on using an alias

答案 2 :(得分:0)

以下是我认为您正在寻找的内容:

select
       patient.`idpatient`
     , comobility.`comobility_items_idcomobility_items`
     , comobilityItems.items
from patient
LEFT JOIN comobility ON patient.`idPatient` = comobility.`idPatient`  
LEFT JOIN comobilityItems ON comobility.idComobilityItems = comobilityItems.idComobilityItems

事情是在机场表上有两个单独的连接,这样你就可以拥有两个不同的机场。否则你将有非常短的航班和非常不满意的乘客。