I have a Category table which has 3 fields i’m interested in:
ID, Name, CategoryType
The root nodes are identified by having CategoryType of 1, subnodes of the root nodes are of type 2 and sub-sub nodes are of type 3.
There’s a 2nd table, CategoryRelationship, of which the two columns that matter are:
CategoryID, ParentCategoryID.
What I would like is a listing of records so that we have the name of each category/subcategory and it’s ID, like below
ID RootName1 ID SubName1 ID Sub-SubName1
ID RootName1 ID SubName1 ID Sub-SubName2
ID RootName1 ID SubName2 ID Sub-SubName1
ID RootName1 ID SubName2 ID Sub-SubName2
ID RootName1 ID SubName2 ID Sub-SubName3
ID RootName2 ID SubName1 ID Sub-SubName1
ID RootName2 ID SubName2
ID RootName2 ID SubName3
The ID would be of each root and node/subnode etc
I think I’ve got this working – i was just wondering if this is the ‘correct’ way of doing this or if this a better way. This is being done against an MS SQL 2012 express db.
select c.id,
c.name,
c1.Name,
cr1.CategoryID,
c2.Name,
cr2.CategoryID
from Category c
left outer join CategoryRelationship cr1 on cr1.CategoryParentID = c.id
left outer join CategoryRelationship cr2 on cr2.CategoryParentID = cr1.CategoryID
inner join Category c1 on c1.ID = cr1.CategoryID
inner join Category c2 on c2.id = cr2.CategoryID
where c.CategoryTypeID = 1
order by c.name, c1.name, c2.name
There’s one more bit to this I need a little help with. There’s a 3rd table that has products in it. Each product has a SubCateoryID which would match up to cr2.CategoryID above. I would like to display the total number of items in the Product table for each cr2 category and i still want to include any categories that have no items in the product table. I’m not sure how to do that last part.
I think I have this: