如何在PostgreSQL中命名具有相同引用的不同列?
我有一个如下所示的routes表:如何在PostgreSQL中命名具有相同引用的不同列?,sql,postgresql,join,Sql,Postgresql,Join,我有一个如下所示的routes表: id | start_point | end_point ----+-------------+----------- 1 | 1 | 2 2 | 1 | 10 3 | 2 | 1 4 | 2 | 5 5 | 2 | 9 9 | 4 |
id | start_point | end_point
----+-------------+-----------
1 | 1 | 2
2 | 1 | 10
3 | 2 | 1
4 | 2 | 5
5 | 2 | 9
9 | 4 | 5
10 | 5 | 2
11 | 5 | 4
12 | 5 | 8
14 | 7 | 8
...
id | start_point | end_point
----+-------------+-----------
1 | New York | Moscow
2 | New York | Tokyo
3 | Moscow | New York
4 | Moscow | Rome
...
location
----------
New York
New York
Moscow
Moscow
...
Moscow
Tokyo
New York
Rome
...
起始点和结束点都引用机场表中的位置列:
机场:
是否有一种方法可以创建一个查询,该查询将使用联接或任何其他解决方案替换位置值的起始点和结束点值,因此结果如下所示:
id | start_point | end_point
----+-------------+-----------
1 | 1 | 2
2 | 1 | 10
3 | 2 | 1
4 | 2 | 5
5 | 2 | 9
9 | 4 | 5
10 | 5 | 2
11 | 5 | 4
12 | 5 | 8
14 | 7 | 8
...
id | start_point | end_point
----+-------------+-----------
1 | New York | Moscow
2 | New York | Tokyo
3 | Moscow | New York
4 | Moscow | Rome
...
location
----------
New York
New York
Moscow
Moscow
...
Moscow
Tokyo
New York
Rome
...
现在我所能做的就是使用此查询在一列中打印start_point和end_point的结果:
select location as departure_point from airports join routes on airports.id = routes.start_point
union all
select location as destination from airports join routes on airports.id = routes.end_point;
看起来是这样的:
id | start_point | end_point
----+-------------+-----------
1 | 1 | 2
2 | 1 | 10
3 | 2 | 1
4 | 2 | 5
5 | 2 | 9
9 | 4 | 5
10 | 5 | 2
11 | 5 | 4
12 | 5 | 8
14 | 7 | 8
...
id | start_point | end_point
----+-------------+-----------
1 | New York | Moscow
2 | New York | Tokyo
3 | Moscow | New York
4 | Moscow | Rome
...
location
----------
New York
New York
Moscow
Moscow
...
Moscow
Tokyo
New York
Rome
...
有什么建议吗?您可以加入airports表两次:一次获取起点位置,另一次获取终点位置:
select
r.id,
s.location start_point,
e.location end_point
from routes r
inner join airports s on s.id = r.start_point
inner join airports e on e.id = r.end_point
您可以加入airports表两次:一次获取起点位置,另一次获取终点位置:
select
r.id,
s.location start_point,
e.location end_point
from routes r
inner join airports s on s.id = r.start_point
inner join airports e on e.id = r.end_point