Work Table
ProductId, LabelName, CategoryId, ChildCategoryId
------------------------------------
1, Widget A, 1, null
null, Category A, 2, 1
2, Widget B, 3, null
Categories Table
CategoryId, CategoryName
---------------------------
1, Category A
2, Category B
3, Category C
Given the information above, how would you get all categories for a product id?
For example, given a product id of 1, the following would be the desired results.
Desired Results
ProductId, LabelName, CategoryId, ChildCategoryId
------------------------------------
1, Widget A, 1, null
null, Category A, 2, 1
null, Category B, null, 2
It is supposed to be hierarchical data and I apologize for not being able to explain very well. It is just boggling my mind. Widget A has a product id of 1 and category id of 1. This means all records that have a ChildCategoryId of 1 is included, which gives us Category A. CatA has a category id of 2, so like before, all records that have a ChildCategoryId of 2 is included in result, which is why Category B is included.
This mess produces the sample result from the sample data. It still isn't clear what you think the algorithm ought to be.
I suspect that the problem is that you have mixed your data in a lopsided manner. A hierarchy of categories is usally represented something like:
The root of each hierarchy is indicated by
ParentCategoryId is NULL
. This allows any number of independent trees to coexist in a single table and does not depend on the existence of any products.If products are assigned to a single (sub)category then just include the
CategoryId
in theProducts
table. If a product may be assigned to several (sub)categories, possibly in different hierarchies, then use a separate table to relate them: