这种混乱会从样本数据中产生样本结果。目前还不清楚你认为算法应该是什么。
declare @CategoryItems as Table (
CategoryName NVarChar(255),
Label NVarChar(255),
ProductId Int,
ChildCategoryId Int,
CategoryId Int );
declare @Categories as Table (
CategoryId Int,
Name NVarChar(100) );
insert into @CategoryItems ( CategoryName, Label, ProductId, ChildCategoryId, CategoryId ) values
( 'CategoryA', 'Widget A', 1, 0, 1 ),
( 'CategoryB', 'CategoryA', 0, 1, 2 ),
( 'CategoryC', 'Widget B', 2, 0, 3 );
insert into @Categories ( CategoryId, Name ) values
( 1, 'CategoryA' ),
( 2, 'CategoryB' ),
( 3, 'CategoryC' );
select * from @Categories;
select * from @CategoryItems;
declare @TargetProductId as Int = 1;
with Leonard as (
-- Start with the target product.
select 1 as [Row], ProductId, Label, CategoryId, ChildCategoryId
from @CategoryItems
where ProductId = @TargetProductId
union all
-- Add each level of child category.
select L.Row + 1, NULL, CI.Label, CI.CategoryId, CI.ChildCategoryId
from @CategoryItems as CI inner join
Leonard as L on L.CategoryId = CI.ChildCategoryId ),
Gertrude as (
-- Take everything that makes sense.
select Row, ProductId, Label, CategoryId, ChildCategoryId
from Leonard
union
-- Then tack on an extra row for good measure.
select L.Row + 1, NULL, C.Name, NULL, C.CategoryId
from Leonard as L inner join
@Categories as C on C.CategoryId = L.CategoryId
where L.Row = ( select Max( Row ) from Leonard ) )
select Row, ProductId, Label, CategoryId, ChildCategoryId
from Gertrude
order by Row;
我怀疑问题在于您以不平衡的方式混合了数据。类别的层次结构通常表示如下:
declare @Categories as Table (
CategoryId Int Identity,
Category NVarChar(128),
ParentCategoryId Int Null );
每个层次结构的根由 表示ParentCategoryId is NULL
。这允许任意数量的独立树共存于单个表中,并且不依赖于任何产品的存在。
如果产品被分配到单个(子)类别,那么只需将 包括CategoryId
在Products
表中。如果一个产品可能被分配到几个(子)类别,可能在不同的层次结构中,那么使用一个单独的表来关联它们:
declare @ProductCategories as Table (
ProductId Int,
CategoryId Int );