0

興味のある 3 つのフィールドを持つカテゴリ テーブルがあります。

ID, Name, CategoryType

ルート ノードは、CategoryType が 1 であることで識別されます。ルート ノードのサブノードはタイプ 2 で、サブサブノードはタイプ 3 です。

2 番目のテーブル、CategoryRelationship があり、重要な 2 つの列は次のとおりです。

CategoryID, ParentCategoryID.

私が望むのは、以下のように、各カテゴリ/サブカテゴリの名前とその ID を持つように、レコードのリストです。

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 

ID は、各ルートおよびノー​​ド/サブノードなどの ID になります。

私はこれが機能していると思います-これがこれを行う「正しい」方法なのか、それともより良い方法なのか疑問に思っていました。これは、MS SQL 2012 Express データベースに対して行われています。

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

これにはもう 1 つ、少し助けが必要です。商品が入っている 3 番目のテーブルがあります。各製品には、上記の cr2.CategoryID に一致する SubCateoryID があります。各 cr2 カテゴリの製品テーブルにアイテムの総数を表示したいと思いますが、製品テーブルにアイテムがないカテゴリも含めたいと考えています。私はその最後の部分を行う方法がわかりません。

4

1 に答える 1

0

私はこれを持っていると思います:

select c.ID, c.Name, c1.Name, cr1.CategoryID, c2.Name, cr2.CategoryID, 
(select count(*) from Product where product.SubcategoryID = cr2.CategoryID and Deleted = 0 and StatusID = 1) 
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
于 2012-07-25T00:25:03.963 に答える