SQL将相同的表连接在一起

时间:2016-04-12 09:14:31

标签: sql join

我想加入两张桌子。他们是一样的。但是我需要加入,因为我在起飞和降落时添加了一个外键约束。他们都参考我的机场表。现在我想显示航班详情,包括起飞机场详情和着陆机场详情。我不知道怎么样?这是我到目前为止,它到目前为止只能显示起飞细节。当我再次尝试添加airport.airport_id时,出现错误。见。

select * 
from flight 
LEFT JOIN route ON flight.route_id = route.route_id 
LEFT JOIN airport ON route.takeoff_id = airport.airport_id

给了我: enter image description here

但是,当我尝试此查询加入着陆详细信息时

select * 
from flight 
LEFT JOIN route ON flight.route_id = route.route_id 
LEFT JOIN airport ON route.takeoff_id = airport.airport_id 
LEFT JOIN airport ON route.land_id = airport.airport_id;

我收到此错误:#1066 - Not unique table/alias: 'airport'

enter image description here

3 个答案:

答案 0 :(得分:2)

当使用同一个表两次(自联接)时,您必须使用表别名来显示您正在谈论的两个中的哪一个的DBMS。

select * 
from flight 
join route ON flight.route_id = route.route_id 
join airport airport_takeoff ON route.takeoff_id = airport_takeoff.airport_id 
join airport airport_landing ON route.land_id = airport_landing.airport_id;

顺便说一下:我已经用内连接替换了你的外连接,因为我认为没有理由在这里连接外连接。你不应该给DBMS做更多的事情。

答案 1 :(得分:0)

要使用同一个表两次,您需要为它们添加别名:

select * 
from flight 
LEFT JOIN route ON flight.route_id = route.route_id 
LEFT JOIN airport a1 ON route.takeoff_id = a1.airport_id 
LEFT JOIN airport a2 ON route.land_id = a2.airport_id;

答案 2 :(得分:0)

尝试以下查询。

    select * 
    from flight  FL  -- alis as FL
    LEFT JOIN route RT ON FL.route_id = RT.route_id 
    LEFT JOIN airport AP1 ON RT.takeoff_id = AP1.airport_id  
    LEFT JOIN airport AP2 ON RT.land_id = AP2.airport_id;

OR

    select * 
    from flight 
    LEFT JOIN route ON flight.route_id = route.route_id 
    LEFT JOIN airport ON route.takeoff_id = airport.airport_id  and route.land_id = airport.airport_id;