繁体   English   中英

SQL 加入同一张表 2 次

[英]SQL join 2 times same table

我有一个飞行表

CREATE TABLE flight (id int, name varchar(25), origin int, destination int);
INSERT INTO flight (id, name, origin, destination) VALUES (1, 'Alpha', 1,2);
INSERT INTO flight (id, name, origin, destination) VALUES (2, 'Beta', 3,4);
...

和机场表一样

CREATE TABLE airport (id int, name varchar(25));
INSERT INTO airport (id, name) VALUES (1, 'Amsterdam');
INSERT INTO airport (id, name) VALUES (2, 'London');
INSERT INTO airport (id, name) VALUES (3, 'Paris');
INSERT INTO airport (id, name) VALUES (4, 'Dubai');
...

我怎样才能得到飞往阿姆斯特丹或从阿姆斯特丹起飞的所有机场?

如果我使用 where 子句WHERE flight.origin = 1 OR flight.destination = 1进行查询,我的结果中也会出现阿姆斯特丹,但没有从阿姆斯特丹到阿姆斯特丹的航班。

使用IN子句:

select *
from airport
where id in (select origin from flight where destination = 1)
   or id in (select destination from flight where origin = 1);

要么

select *
from airport
where id in 
(
  select origin from flight where destination = 1
  union all
  select destination from flight where origin = 1
);

(您当然可以将= 1替换为= (select id from airport where name = 'Amsterdam') 。)

您可以使用EXISTS

select a.* from airport a
where a.id <> 1
and exists (
  select 1 from flight f
  where a.id in (f.origin, f.destination) and 1 in (f.origin, f.destination)
)

请参阅演示
结果:

> id | name  
> -: | :-----
>  2 | London

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM