This is not a duplicate question as the above link simply creates the same problem i am trying to answer
I have a simple table in phpmyadmin consisting of category id, the name of the category and its parent category id, thus the columns are labeled: id,name,parentid
Example data:
id name parentid
1 animal NULL
2 vegetable NULL
3 mineral NULL
4 doggie 1
5 kittie 1
6 horsie 1
7 gerbil 1
8 birdie 1
9 carrot 2
10 tomato 2
11 potato 2
12 celery 2
13 rutabaga 2
14 quartz 3
15 feldspar 3
16 silica 3
17 gypsum 3
18 hunting 4
19 companion 4
20 herding 4
21 setter 18
22 pointer 18
23 terrier 18
24 poodle 19
25 chihuahua 19
26 shepherd 20
27 collie 20
I would like to output all category paths and the id of each. So far i can create the path with the following sql:
select root.name as root_name
, down1.name as down1_name
, down2.name as down2_name
, down3.name as down3_name
from categories as root
left outer
join categories as down1
on down1.parentid = root.id
left outer
join categories as down2
on down2.parentid = down1.id
left outer
join categories as down3
on down3.parentid = down2.id
where root.parentid is null
order
by root_name
, down1_name
, down2_name
, down3_name
All i want to add to the output is the ID of each category along with its path. I found the above code at: http://sqllessons.com/categories.html
The above code creates the following:
root_name down1_name down2_name down3_name
animal birdie NULL NULL
animal doggie companion chihuahua
animal doggie companion poodle
animal doggie herding collie
animal doggie herding shepherd
animal doggie hunting pointer
animal doggie hunting setter
animal doggie hunting terrier
animal gerbil NULL NULL
animal horsie NULL NULL
animal kittie NULL NULL
mineral feldspar NULL NULL
mineral gypsum NULL NULL
mineral quartz NULL NULL
mineral silica NULL NULL
vegetable carrot NULL NULL
vegetable celery NULL NULL
vegetable potato NULL NULL
vegetable rutabaga NULL NULL
vegetable tomato NULL NULL
However, i want it to create the following:
id root_name down1_name down2_name down3_name
8 animal birdie NULL NULL
25 animal doggie companion chihuahua
24 animal doggie companion poodle
27 animal doggie herding collie
26 animal doggie herding shepherd
22 animal doggie hunting pointer
21 animal doggie hunting setter
23 animal doggie hunting terrier
7 animal gerbil NULL NULL
6 animal horsie NULL NULL
5 animal kittie NULL NULL
15 mineral feldspar NULL NULL
17 mineral gypsum NULL NULL
14 mineral quartz NULL NULL
16 mineral silica NULL NULL
9 vegetable carrot NULL NULL
12 vegetable celery NULL NULL
11 vegetable potato NULL NULL
13 vegetable rutabaga NULL NULL
10 vegetable tomato NULL NULL
Baring in mind that the above is from the above link and the the real data could contain upto 6 levels of subcategories deep.
Thanks for your help
John