父子关系的SQL查询 [英] SQL Query for Parent Child Relationship
本文介绍了父子关系的SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据库表的父子关系为:
I have db table with parent child relationship as:
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查询,该查询将在父类别的所有级别返回子代.
Here parentId = 0 means that it is a root level node. Now I want to write an SQL Query which will return child at all level of a parent category.
例如对于nodeId = 1,应返回3、4、5、6.
e.g. for nodeId = 1, it should return 3, 4, 5, 6.
我正在使用MS SQL Server 2005
I am using MS SQL Server 2005
推荐答案
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]
这篇关于父子关系的SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文