Chain of Linked Tables
Now suppose users live in certain cities, and these cities are located in different countries. In this case, for storage we will need three tables: users will be linked to cities, and cities - to countries. At the same time, we won't need a field linking users to countries - because users will already be linked to countries through the link between cities and countries.
Let's look at our tables. The table with countries:
| id | name |
|---|---|
| 1 | country1 |
| 2 | country2 |
The table with cities:
| id | name | country_id |
|---|---|---|
| 1 | city1 | 1 |
| 2 | city2 | 1 |
| 3 | city3 | 2 |
The table with users will remain unchanged:
| id | name | city_id |
|---|---|---|
| 1 | user1 | 1 |
| 2 | user2 | 1 |
| 3 | user3 | 2 |
| 4 | user4 | 1 |
| 5 | user5 | 3 |
| 6 | user6 | 2 |
Queries
In order to get users along with their cities and countries, we will have to make two joins: the first will join cities to users, and the second - countries to cities:
SELECT
users.name,
cities.name as city_name,
countries.name as country_name
FROM
users
LEFT JOIN cities ON cities.id=users.city_id
LEFT JOIN countries ON countries.id=cities.country_id
Practical Tasks
Suppose products belong to a certain subcategory, and subcategories belong to a certain category. Describe the storage structure.
Write a query that will fetch products, along with their subcategories and categories.
Write a query that will fetch subcategories along with their categories.