答案是使用recusive“Common Table Expression”或CTE。这使您可以构建层次结构。下面是一个例子,修改,以符合您的结构,基于此页上:http://msdn.microsoft.com/en-us/library/ms186243.aspx
WITH CategoryStructured (ParentCategoryID, CategoryID, Description, Status, Level)
AS
(
-- Anchor member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
0 AS Level
FROM Category AS c
WHERE c.ParentCategoryID=0
UNION ALL
-- Recursive member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
Level + 1
FROM Category AS c
INNER JOIN CategoryStructured AS c_parent
ON c.ParentCategoryID = c_parent.CategoryID
)
-- Statement that executes the CTE
SELECT distinct cs.ParentCategoryID, cs.CategoryID, cs.Description, cs.Status, cs.Level
FROM
CategoryStructured cs,
(SELECT level,ParentCategoryID,CategoryID from CategoryStructured WHERE (categoryID = 4) OR (level = 1 AND parentCategoryID = 4)) as thisCategory
WHERE cs.level BETWEEN thisCategory.level - 1 AND thisCategory.level+1
AND ((thisCategory.level != 0 AND cs.ParentCategoryID = thisCategory.ParentCategoryID)
OR cs.categoryID = thisCategory.ParentCategoryID
OR cs.ParentCategoryID = thisCategory.CategoryID
OR cs.CategoryID = thisCategory.CategoryID)
更新,以反映更新后的问题。
编辑我知道你能得到上述基本为你工作与添加的不同,但我想到了一个更好的方式来处理这个问题后,我离开了聊天:
WITH CategoryStructured (ParentCategoryID, CategoryID, Description, Status, Level)
AS
(
-- Anchor member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
0 AS Level
FROM Categories AS c
WHERE
(c.ParentCategoryID IS NULL AND c.categoryID = 7) -- when 7 is a top level category, then it is the root level
OR (c.categoryID = (SELECT c2.parentCategoryID FROM Categories c2 WHERE c2.categoryID = 7)) -- when 7 is some non-top level category, then 7's parent is the root
UNION ALL
-- Recursive member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
Level + 1
FROM Categories AS c
INNER JOIN CategoryStructured AS c_parent
ON c.ParentCategoryID = c_parent.CategoryID
)
-- Statement that executes the CTE
SELECT cs.ParentCategoryID, cs.CategoryID, cs.Description, cs.Status, cs.Level
FROM
CategoryStructured cs
WHERE cs.level < 3
ORDER BY cs.level
它将只返回子女,子女,但我想父母,兄弟姐妹也 – rahularyansharma 2011-12-23 05:09:24
我不明白 - 这返回整个表,每个级别确定。有什么问题? – 2011-12-23 05:24:30
我现在检查它对不起之前的评论我忘了关于水平现在我不得不查询这张表为我想要的结果 – rahularyansharma 2011-12-23 05:27:31