关于网友提出的“ SQL 实现二叉树”问题疑问,本网通过在网上对“ SQL 实现二叉树”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: SQL 实现二叉树
描述: 图1:

图2:

这是我通过查询出来的一个类似二叉树的结构,但是其中子分支是可以相同的,
这样导致了一个问题,我在前端做展示的时候,同一个父级会挂上多个相同的
子分支,所以我的思路是给
1.通过再次写sql每个分支做分组,如图1
2.通过再次写sql确定每个节点id的唯一性,如图2
或者大家给个思路如果解决类似的问题
解决方案1: mssql2008 出了一个新的数据类型 hierarchyid,主要解决的问题就是是拥有层次关系的表格,和适合你的需求。
解决方案2: 怎么有的节点又属于组一也属于组二。这样分组查出的结果是这样的
with tree(ID,CurrentID,StrID,ParentID)AS(
select 1,0,'a1','0' union all
select 2,0,'a2','0' union all
select 5,2,'c5','a2' union all
select 4,3,'d4','c5' union all
select 2,1,'b2','a1' union all
select 5,2,'c5','b2' union all
select 4,3,'d4','c5'
),cte AS (
select ID,StrID,CurrentID,ParentID,row_number()over(Order By ID) as GroupID from tree where ParentID='0'
UNION ALL
select t.ID,t.StrID,t.CurrentID,t.ParentID,cte.GroupID from tree as t inner join cte on cte.StrID=t.ParentID
)
select * from cte
ID StrID CurrentID ParentID GroupID
1 1 a1 0 0 1
2 2 a2 0 0 2
3 5 c5 2 a2 2
4 4 d4 3 c5 2
5 4 d4 3 c5 2
6 2 b2 1 a1 1
7 5 c5 2 b2 1
8 4 d4 3 c5 1
9 4 d4 3 c5 1
以上介绍了“ SQL 实现二叉树”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/4276562.html