Target platform: MySQL 5.7
I have table categories
that represents hierarchical categories data:
+----+-----------------+-----------+
| id | name | parent_id |
+----+-----------------+-----------+
| 1 | First category | NULL |
| 2 | Second category | 1 |
| 3 | Third category | 2 |
| 4 | Other category | 1 |
+----+-----------------+-----------+
Also, I have another table (categories_relations
) that stores relations between category and all other related (or connected) categories:
+----+-----------+-------------+
| id | parent_id | relation_id |
+----+-----------+-------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 2 | 2 |
| 6 | 2 | 3 |
| 7 | 3 | 3 |
| 8 | 4 | 4 |
+----+-----------+-------------+
Is it possible to retrieve filtered categories (for example - by ID) with all related other categories? For example, if I would query category with ID=1, query result should be:
+----+-----------------+-----------+
| id | name | parent_id |
+----+-----------------+-----------+
| 1 | First category | NULL |
| 2 | Second category | 1 |
| 3 | Third category | 2 |
| 4 | Other category | 1 |
+----+-----------------+-----------+
If ID=4:
+----+-----------------+-----------+
| id | name | parent_id |
+----+-----------------+-----------+
| 1 | First category | NULL |
| 4 | Other category | 1 |
+----+-----------------+-----------+
And so on. Thank you.