I have a category tree that is structured in two ways: Every category has a path and a parentID. The path is made from the IDs (bottom to top) of the categories. The parentID references another category. So my table look like this:
id | name | path | parentID
---+-------------+---------+---------
1 | Root | NULL | NULL
2 | Main | NULL | 1
3 | Electronics | |2| | 2
4 | Computers | |3|2| | 3
5 | PCs | |4|3|2| | 4
6 | Macs | |4|3|2| | 4
7 | Cameras | |3|2| | 3
8 | Canon | |7|3|2| | 7
Now I don't need the categories 'Root' and 'Main'. What I try to achieve is an output like this:
id | resolved_path
---+-----------------------------
3 | Electronics
4 | Electronics_Computers
5 | Electronics_Computers_PCs
6 | Electronics_Computers_Macs
7 | Electronics_Cameras
8 | Electronics_Cameras_Canon
So I have a varying depth and I need the categories to be in reversed order. I didn't really find much about this online. All I got is this snippet which shows the depth of the category:
SELECT
*,
(ROUND(
(LENGTH(cat.path) - LENGTH(REPLACE(cat.path, '|', ''))) / LENGTH('|')
) - 2) depth
FROM
categories cat
WHERE
cat.path IS NOT NULL
I don't know what is easier: going through the parentIDs recursively or doing some magic to the paths.