I have a database setup named "Categories', where categories can be created and have a parent set. A parent category would be set to "0" under the Parent column, where the id would be used to set its subcategory.
The nested categories can be 4 categories deep:
Parent >> Subcategory >> subcategory >> subcategory
I have the query setup as so:
SELECT *,
cat_a.id AS A_ID, cat_a.Title AS A_Title, cat_a.Parent AS A_Parent,
cat_b.id AS B_ID, cat_b.Title AS B_Title, cat_b.Parent AS B_Parent,
cat_c.id AS C_ID, cat_c.Title AS C_Title, cat_c.Parent AS C_Parent,
cat_d.id AS D_ID, cat_d.Title AS D_Title, cat_d.Parent AS D_Parent
FROM Categories AS cat_a
LEFT JOIN Categories AS cat_b
ON cat_a.Parent = cat_b.id
LEFT JOIN Categories AS cat_c
ON cat_b.Parent = cat_c.id
LEFT JOIN Categories AS cat_d
ON cat_c.Parent = cat_d.id
WHERE cat_a.Username='$UserID'
GROUP BY cat_a.id
This displays the information as needed, but the ordering isn't correct. I'm looking to have the nested displayed so each subcategory with a parent will loop directly under it, like so:
Universe
-> Milky Way
--> Planets
---> Earth
---> Mars
--> Moons
---> Titan
---> Europa
-> Andromeda
--> Unknown Planets
---> Planet X
etc..
Thanks for your time!
If I understand the data structure correctly, you don't need the group by
. Instead, use:
order by cat_a.id, cat_b.id, cat_c.id, cat_d.id