Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi There,

Hi all, I have a category structure and I need to count the category levels based on the parent_id.

For example:

cname ¦cid ¦ category_parent_id
cat 1 ¦ 1 ¦ 0
cat 2 ¦ 2 ¦ 0
cat 3 ¦ 3 ¦ 1
cat 4 ¦ 4 ¦ 1
cat 5 ¦ 5 ¦ 3
cat 6 ¦ 6 ¦ 3
cat 7 ¦ 7 ¦ 4
cat 8 ¦ 8 ¦ 0
cat 9 ¦ 9 ¦ 8
cat 10 ¦ 10 ¦ 8
cat 11 ¦ 11 ¦ 0
cat 12 ¦ 12 ¦ 11
cat 13 ¦ 13 ¦ 11
cat 14 ¦ 14 ¦ 0

I need to count cat 6 has a category_parent_id of 3 and cat 3 has a category_parent_id of 1 so this should count 3 times making it 3 levels deep.


I cant work out how to count the repeated occurrences of a category based on it's parent.

Thanks for any advice.
Posted
Comments
wizardzz 26-Mar-12 11:30am    
Not sure what you are stuck on? What do you meant by count? It doesn't seem to be the right term here.

1 solution

Recursive selects are your friend here;
SQL
with t as
(
	select * from testtbl as t1
	union all
	select t2.* from testtbl as t2
	join t on t.cid=t2.category_parent_id
)
select cname, count(1) as depth from t
group by cname


I haven't got access to a MySql instance here so I've only tested that on SQLServer.

Hope this helps,
Fredrik

Actually, ignore of all that. MySQL doens't support it I think :(
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900