获取父类别的分层类别

时间:2013-11-25 16:01:06

标签: sql sql-server hierarchical-data

我需要一个查询,他选择具有给定父ID的所有子类别。我的表如下所示:

|ID | Title | Description | ParentId
--------------------------------------
 1  | Games | ...         | NULL

依旧......

是否可以使用sql-query解决此问题?

给我类别游戏的所有儿童类别..

所有子类别都可以包含更多子类别等等。

我需要在我的网站菜单中列出产品..
我的尝试 使用CocoDb 去

;WITH parent 
  AS ( SELECT ParentId 
       FROM [CocoDb].[dbo].[Categories] 
       WHERE Id = 11 ) 
,tree AS ( SELECT x.ParentId, x.Id 
           FROM [CocoDb].[dbo].[Categories] x 
                 INNER JOIN [CocoDb].[dbo].[Categories] ON x.Id = 11
            UNION ALL 
           SELECT y.Id, y.ParentId FROM [CocoDb].[dbo].[Categories] y 
             INNER JOIN [CocoDb].[dbo].[Categories] t ON y.Id = t.ParentId )

解决方案:

;WITH parent 
  AS ( SELECT ParentId, Title, Id 
       FROM [CocoDb].[dbo].[Categories] 
       WHERE Id = 1
      ) 
,tree AS ( 
           SELECT x.ParentId, x.Id, x.Title 
           FROM [CocoDb].[dbo].[Categories] x 
                 INNER JOIN parent ON x.ParentId = parent.Id
           UNION ALL 
           SELECT y.ParentId, y.Id, y.Title 
           FROM [CocoDb].[dbo].[Categories] y 
            INNER JOIN tree t ON y.ParentId = t.Id 
          )
SELECT *
FROM Tree

2 个答案:

答案 0 :(得分:1)

;WITH parent AS 
    (
    SELECT Parent
    FROM Table1
    WHERE Child = @p0
    )    
,tree AS 
    (
    SELECT x.Parent, x.Child
    FROM Table1 x
    INNER JOIN parent ON x.Parent = parent.Parent
    UNION ALL
    SELECT y.Parent, y.Child
    FROM Table1 y
    INNER JOIN tree t ON y.Parent = t.Child
    )
      SELECT Parent, Child
      FROM tree

更新您的查询

;WITH parent 
  AS ( SELECT ParentId 
       FROM [CocoDb].[dbo].[Categories] 
       WHERE Id = 11 
      ) 
,tree AS ( 
           SELECT x.ParentId, x.Id 
           FROM [CocoDb].[dbo].[Categories] x 
                 INNER JOIN parent ON x.ParentId = parent.ParentId
           UNION ALL 
           SELECT y.ParentId, y.Id 
           FROM [CocoDb].[dbo].[Categories] y 
            INNER JOIN tree t ON y.ParentId = t.Id 
          )
SELECT parent, Child 
FROM Tree

请确保在;之前使用WITH,就像我在上述查询中使用的一样。

答案 1 :(得分:0)

SELECT C.*
FROM <TABLE> C INNER JOIN <TABLE> P
ON P.ID=C.PARENTID
WHERE PARENTID=<GIVEN PARENTID>