父子关系的SQL查询

时间:2008-10-16 03:08:35

标签: sql sql-server-2005 hierarchical-data

我有父子关系的db表:

NodeId    NodeName    ParentId
------------------------------
1         Node1       0
2         Node2       0
3         Node3       1
4         Node4       1
5         Node5       3
6         Node6       5
7         Node7       2

这里parentId = 0表示它是根级节点。现在我想编写一个SQL查询,它将在父类别的所有级别返回子级。

e.g。对于nodeId = 1,它应该返回3,4,5,6。

我正在使用MS SQL Server 2005

4 个答案:

答案 0 :(得分:10)

with [CTE] as (
    select * from [TheTable] c where c.[ParentId] = 1
    union all
    select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]
)
select * from [CTE]

答案 1 :(得分:6)

您应该考虑在SQL数据库中使用嵌套集模型来实现父子关系。它比尝试在表中存储记录的parentID要好得多,并使这样的查询更容易。

答案 2 :(得分:4)

只是为了确保它是否是它自己的父级(否则它会递归直到它中断):

   with [CTE] as (
        select * from [TheTable] c where c.[ParentId] = 1
        union all
        select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]
        and c.[ParentId] <> c.[NodeId]
    )
    select * from [CTE]

答案 3 :(得分:1)

 WITH Temp_Menu AS
 ( 
  SELECT AM.* from FCB_AccessMenu AM where AM.[ParentId] = 6   

           UNION ALL     

        SELECT AM.* FROM  FCB_AccessMenu AM ,Temp_Menu TM  WHERE AM.[ParentID]=TM.[MenuID]        

  )   

  SELECT * FROM Temp_Menu ORDER BY ParentID