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ます。これにより、任意の数の独立したツリーを 1 つのテーブルに共存させることができ、製品の存在に依存しません。

製品が 1 つの (サブ) カテゴリに割り当てられている場合はCategoryIdProductsテーブルに を含めます。製品が複数の (サブ) カテゴリに割り当てられている可能性があり、異なる階層にある可能性がある場合は、別のテーブルを使用してそれらを関連付けます。

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