SQL 查询问题,如何做一个输出两个表所有条目的查询

SQL query question, how to make a query that outputs all entries of two tables

我有两个表,CITIESFLIGHTS:

城市

id name
1 New York
2 Paris
3 Tokyo
4 Amsterdam

航班

id departure_id arrival_id
1 1 2
2 1 3
3 2 3
4 2 4

我需要编写一个查询来查找所有航班连接。

所需的输出将是:

departure_city arrival_city
New York Paris
New York Tokyo
Paris Tokyo
Paris Amsterdam

如何写这个查询?

您可以为此使用加入。 inner join 和 left join 都可以满足您的目的:

使用左连接查询:

Select c.name as departure_city, ct.name as arrival_city from FLIGHTS f 
left join CITIES c on f.departure_id=c.id
left join CITIES ct on f.arrival_id = ct.id

输出:

departure_city arrival_city
New York Paris
New York Tokyo
Paris Tokyo
Paris Amsterdam

内连接查询:

Select c.name as departure_city, ct.name as arrival_city from FLIGHTS f 
inner join CITIES c on f.departure_id=c.id
inner join CITIES ct on f.arrival_id = ct.id

输出:

departure_city arrival_city
New York Paris
New York Tokyo
Paris Tokyo
Paris Amsterdam

db<>fiddle here

您可以进行两个连接:

SELECT departure.name AS departure, 
arrival.name AS arrival
FROM cities AS departure 
JOIN flights f ON departure.id = f.departure_id
JOIN cities arrival ON arrival.id = f.arrival_id;

没有进一步的信息,不清楚你是想做左连接还是内连接,是否需要 where 子句,是否需要 order by 等等。也许学习一些会更好 SQL基础知识,然后在必要时提出更精确的问题。 如果你想试试:db<>fiddle

您也可以使用下面的 SQL:

SELECT c1.NAME, c2.NAME FROM CITIES c1, CITIES c2, flights f WHERE c1.id = f.departure_id AND c2.id = f.arrival_id;

准备好的语句如下:

CREATE TABLE CITIES(id int, name varchar(32));

INSERT INTO CITIES values(1, 'New York'), (2, 'Paris'), (3, 'Tokyo'), (4, 'Amsterdam');

CREATE TABLE FLIGHTS(id int, departure_id int, arrival_id int);

INSERT INTO FLIGHTS VALUES(1,1,2), (2,1,3), (3,2,3), (4,2,4);