【问题标题】:display sub categories using SQL使用 SQL 显示子类别
【发布时间】:2012-07-08 06:06:42
【问题描述】:

好吧,这有点令人困惑,所以我决定写一个新问题。

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

父类别的 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 条记录“计算机”。那么您到底在寻找什么?
  • 希望返回子类别,以便我可以在中继器控件中使用它们。因此,当用户将鼠标悬停在父项上时,子项就会出现。
  • 好的,然后看我答案的底部 - 你想要 ParentCategoryID = 10

标签: sql sql-server-2008 nopcommerce


【解决方案1】:

自连接回表以查找孩子的实际父母。

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)

【讨论】:

  • 我可以做 ParentCategoryID > 0
  • 从头开始,我需要传递一个值来确定 ParentCategoryID 以显示子类别。
  • 亲爱的,你在周末指导了我。这个世界上应该有更多像你这样的人。太感谢了! :)
  • 返回父级然后是子级、父级然后是子级的查询怎么样。或者考虑到我目前的设置,这不可能吗?
  • 实际上也是如此,当您运行基本的选择查询时,系统看起来已经像这样分组了。
猜你喜欢
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多