首页 > 解决方案 > 存在函数

问题描述

我正在尝试回答以下查询

编写一个查询,显示所有航班的航班号 (flno)、始发地和目的地,其中存在另一个从目的地返回始发地的航班。

select distinct flno, origin, destination as d from flight 
where exists (select flno, destination from flight where origin = d)

前两个答案是正确的,但它给了我更多与问题无关的答案?

飞行表:

在此处输入图像描述

标签: sqlsqlitesubquerywhere-clause

解决方案


您需要将条件中的子查询与外部查询相关联。exists你出现的逻辑似乎是:

select flno, origin, destination
from flight f
where exists (
    select 1 
    from flight f1 
    where f1.origin = f.destination and f1.destination = f.origin
)

推荐阅读