问题描述
我正在尝试回答以下查询
编写一个查询,显示所有航班的航班号(flno),始发地和目的地,其中存在另一个从目的地返回到始发地的航班。
select distinct flno,origin,destination as d from flight
where exists (select flno,destination from flight where origin = d)
前两个答案是正确的,但是它给了我更多与问题无关的答案?
航班表:
解决方法
您需要将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
)
,
这是一种无需使用子查询即可解决上述查询的简便方法:
select flno,destination from flight f1,flight f2
where fl.origin = f2.destination and f1.destination = f2.origin