使用SQL显示子类别

时间:2012-07-08 16:59:13

标签: sql sql-server-2008 nopcommerce

好的,这让人感到困惑所以我决定写一个新问题。

我需要检查类别表中的一行是否属于子类别。然后我需要检查孩子属于哪个父类别?

父类别的categoryID和ParentCategoryID为0 子类别具有categoryID和ParentCategoryID,例如30。

类别表:

ID PCID NAME
10  0   Computers
11  10  Software
12  10  Hardware

这是我尝试过的:

这将显示父类别(因为PCID 0是父类):

SELECT        CategoryID, ParentCategoryID, Name, Published, Deleted, PictureID
FROM          Nop_Category
WHERE        (Deleted = 0) 
AND          (Published = 1) 
AND          (ParentCategoryID = 0)

1 个答案:

答案 0 :(得分:4)

自我联接回到桌面以找到孩子的实际父母。

SELECT        c1.CategoryID, c2.ParentCategoryID, c1.Name, c2.Name as ParentName, c1.Published, c1.Deleted, c1.PictureID
FROM          Nop_Category c1
JOIN          Nop_Category c2 on c1.ParentCategoryId = c2.CategoryId
WHERE        (c1.Deleted = 0)  
AND          (c1.Published = 1)  
AND          (c1.ParentCategoryID = 10)

这将返回“计算机”类别的两个孩子。这就是你要找的东西吗?

当然,你可以转过来展示特定父母或所有父母的所有孩子:

SELECT c.*, p.* -- shortened, but you should pick specific columns

FROM Nop_Category p -- parent
JOIN Nop_Category c ON c.ParentCategoryId = p.CategoryId -- children

WHERE p.ParentCategoryId = 0 -- all top level parents


SELECT c.*, p.* -- shortened, but you should pick specific columns

FROM Nop_Category p -- parent
JOIN Nop_Category c ON c.ParentCategoryId = p.CategoryId -- children

WHERE p.CategoryId = 10 -- only the "Computers" category

或者,如果您只想要“计算机”类别的子项,请将您的ParentCategoryId更改为10

SELECT        CategoryID, ParentCategoryID, Name, Published, Deleted, PictureID  
FROM          Nop_Category  
WHERE        (Deleted = 0)   
AND          (Published = 1)   
AND          (ParentCategoryID = 10)