0

好的,这变得令人困惑,所以我决定写一个新问题。

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

父类别的 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)
4

1 回答 1

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)
于 2012-07-08T17:09:05.850 回答