2012-07-24 57 views
0

我有3場我感興趣的類別表:SQL類別樹 - 類,categoryrelationship和產品表 - 產品需求總量爲每個SUBCAT

ID, Name, CategoryType 

根節點由具有鑑定的1 CategoryType,根節點的子節點是2型和子 - 子節點是類型3

有一個第二表,CategoryRelationship,其中兩列是重要的:

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將每一根和節點/子節點等

我想我有這個工作 - 我只是想知道這是否是這樣做的「正確」方式,或者如果這是一個更好的方法。這是針對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 

還有一點點,我需要一點幫助。有第三張桌上有產品。每個產品都有一個SubCateoryID,它可以匹配上面的cr2.CategoryID。我想爲每個cr2類別顯示產品表中的項目總數,並且我仍然希望在產品表格中包含任何沒有項目的類別。我不知道如何做最後一部分。

+1

由於您使用MS SQL,你可以嘗試使用公用表表達式。看看[這](http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/DSNAPJ10/APPENDIX1.5?DT=20040210163115#TBLWQ1040) – arunmoezhi 2012-07-25 00:31:14

+0

是否有理由使用一個超過其他?我設法使用我在提交的答案中發佈的sql來工作。但是有沒有性能提升或其他理由來使用您提供的示例?還是隻是另一種方式呢?並感謝您的信息 – merk 2012-07-26 00:59:56

回答

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