I have a table (models) that I want to loop through. It have a column called category, linked to another table (categories).
id name parent
1 Audio NULL
2 Video NULL
3 Monitor 2
4 Monitor 1
5 Light NULL
6 HD 3
7 4K 4
with the sql below I get the name of the level but I would like to get the whole path to be able to sort based on the full category path. For example id 7 now gives me "4K" but I would like to get "Video / Monitor / 4K", id 4-> "Audio / Monitor". As you see there can be sub categories with the same name.
SELECT
m.id AS Id,
c.name AS Category,
m.model AS Model
FROM models m
LEFT JOIN categories c ON m.category=c.id
GROUP BY m.id
ORDER BY Category
For the moment I have a php loop that starts with the id in the models table, then checks if the parent is NULL, makes a new sql and so on until parent is NULL. There must be a better way to do it?
UPDATE: The server is running MySQL 5.6 and it can not be updated for now
UPDATE 2: I saw the suggested duplicate before but in my case I know the id of the child and I want to find all parents.