0

开始摆弄

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

鉴于上述信息,您将如何获取产品 ID 的所有类别?

例如,给定产品 id 为 1,以下将是所需的结果。

Desired Results
ProductId, LabelName, CategoryId, ChildCategoryId
------------------------------------
1, Widget A, 1, null
null, Category A, 2, 1 
null, Category B, null, 2

它应该是分层数据,我很抱歉无法很好地解释。这简直让我难以置信。小部件 A 的产品 id 为 1,类别 id 为 1。这意味着包含 ChildCategoryId 为 1 的所有记录,这为我们提供了类别 A。CatA 的类别 id 为 2,因此与之前一样,所有具有结果中包含 2 的 ChildCategoryId,这就是包含类别 B 的原因。

4

1 回答 1

1

这种混乱会从样本数据中产生样本结果。目前还不清楚认为算法应该是什么。

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。这允许任意数量的独立树共存于单个表中,并且不依赖于任何产品的存在。

如果产品被分配到单个(子)类别,那么只需将 包括CategoryIdProducts表中。如果一个产品可能被分配到几个(子)类别,可能在不同的层次结构中,那么使用一个单独的表来关联它们:

declare @ProductCategories as Table (
  ProductId Int,
  CategoryId Int );
于 2013-09-06T00:52:07.257 回答