I'm learning MySQL for the first time, and I've been able to figure things out so far, but I've ran into a practice assignment that I just can't seem to wrap my head around.
I've viewed multiple similar issues here, but I've had trouble adapting them to my own situation.
I have two tables:
Cities
+----+-----------+
| id | name |
+----+-----------+
| 1 | Helsinki |
+----+-----------+
| 2 | Stockholm |
+----+-----------+
| 3 | Oslo |
+----+-----------+
| 4 | London |
+----+-----------+
Flights
+----+---------+----------+
| id | from_id | to_id |
+----+---------+----------+
| 1 | 1 | 2 |
+----+---------+----------+
| 2 | 1 | 3 |
+----+---------+----------+
| 3 | 2 | 3 |
+----+---------+----------+
| 4 | 2 | 4 |
+----+---------+----------+
| 5 | 1 | 2 |
+----+---------+----------+
| 6 | 2 | 1 |
+----+---------+----------+
| 7 | 1 | 3 |
+----+---------+----------+
| 8 | 3 | 1 |
+----+---------+----------+
I want to create a query which has an end result like this:
+-----------+-----------+
| FROM | TO |
+-----------+-----------+
| Helsinki | Stockholm |
+-----------+-----------+
| Helsinki | Oslo |
+-----------+-----------+
| Stockholm | Oslo |
+-----------+-----------+
| Stockholm | London |
+-----------+-----------+
| Helsinki | Stockholm |
+-----------+-----------+
| Stockholm | Helsinki |
+-----------+-----------+
| Helsinki | Oslo |
+-----------+-----------+
| Oslo | Helsinki |
+-----------+-----------+
Basically I just want to replace the id numbers with city names, but I want to do this only in the query, don't want to replace any values in the data itself. How do I achieve this?
Here you can find a test case for my situation: http://sqlfiddle.com/#!9/7475a2/5/0
It should come with everything necessary for creating and populating the tables and also one of the many queries I've tried, but which I had no success with.
Links to some similar topics I've looked at:
- MySQL JOIN to replace IDs with value from another table
- SQL Replace multiple variables from another table in query result
- Replaces id with a value from another table
Even after trying to adapt solutions from these topics, and reading up on "SELECT" and "JOIN", I can't get it right.