code_monkey
code_monkey

Reputation: 39

How to name different columns with the same reference in PostgreSQL?

I have a routes table that looks like this:

 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
...

Both the start_point and end_point refers to a location column from airports table:

Foreign-key constraints:
    "routes_end_point_fkey" FOREIGN KEY (end_point) REFERENCES airports(id) ON DELETE CASCADE
    "routes_start_point_fkey" FOREIGN KEY (start_point) REFERENCES airports(id) ON DELETE CASCADE

airports:

  Column  |         Type          | Collation | Nullable |               Default
----------+-----------------------+-----------+----------+--------------------------------------
 id       | bigint                |           | not null | nextval('airports_id_seq'::regclass)
 location | character varying(20) |           | not null |

Is there a way to create a query that will replace start_point and end_point values on values from location using joins (or any other solution), so result would be something like this:

 id | start_point | end_point
----+-------------+-----------
  1 |    New York |    Moscow
  2 |    New York |     Tokyo
  3 |      Moscow |  New York
  4 |      Moscow |      Rome
...

All I could do by now is to print the results from both start_point and end_point in one column with this query:

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;

So it looks like this:

 location
----------
 New York 
 New York 
 Moscow   
 Moscow   
...
 Moscow   
 Tokyo    
 New York 
 Rome     
...

Any suggestions?

Upvotes: 1

Views: 44

Answers (1)

GMB
GMB

Reputation: 222632

You can join the airports table twice: once to get the location of the start point, another time to get the location of the end point:

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

Upvotes: 4

Related Questions