比较两个表中的两个选择

时间:2018-10-06 20:14:29

标签: sql database postgresql

我需要随国际航班出发返回 城市

我知道这是不正确的,但这是我到目前为止所掌握的。

SELECT 
    flight.departurecity 
FROM 
    flight 
INNER JOIN 
    airport ON flight.departurecity = airport.city 
WHERE 
    (SELECT airport.nation WHERE flight.departurecity = airport.city) != 
        (SELECT airport.nation WHERE flight.arrivalcity = airport.city)

机场表:

airport table

航班表:

flight table

2 个答案:

答案 0 :(得分:1)

SELECT DISTINCT
    flight.departurecity 
FROM 
    flight 
INNER JOIN 
    airport a1 ON flight.departurecity = a1.city 
INNER JOIN 
    airport a2 ON flight.arrivalcity = a2.city 
WHERE 
    a1.nation != a2.nation;

经修正和修改的版本,戈登·利诺夫(Gordon Linoff)暗示我的意思是

select a.*
from airport a
where exists (select *
              from flight f join
                   airport a2 on f.arrivalCity = a2.city
              where f.departureCity = a.city
                    and a2.nation <> a.nation
             );

答案 1 :(得分:0)

我只会去:

select a.*
from airport a
where exists (select 1
              from flight f join
                   airport a2
              where f2.arrivalcity = a2.city and
                    f2.departurecity = a.city and
                    a2.nation <> a.nation
             );

请注意,这不需要select distinct,除非您确实想要一个城市列表而不只是机场列表。因此,它应该比双join版本要快得多。