create table A(aID int identity(1,1),baseid int,[name] varchar(20))
create table B(bID int identity(1,1),parentId int,childId int)
insert A
select 1,'aaa' union all
select 2,'bbb' union all
select 3,'ccc' union all
select 4,'a1' union all
select 5,'a2' union all
select 6,'b1' union all
select 7,'aa1' union all
select 8,'dsdssd'
insert B
select 1,4 union all
select 1,5 union all
select 4,7 union all
select 7,8
注:A.baseId = B.parentId
表B中的childId对应A表的Id,意思就是说A表存了所有数据,包括所以节点,而B只存有关系.
树结构如下:
---1
---4
---7
---8
---5
---2
---3
---6
现在假如获取顶层节点和第一子节点,请问怎么解决。
------最佳解决方案--------------------
整理一下格式加点注释
--create table A(aID int identity(1,1),baseid int,[name] varchar(20))
--create table B(bID int identity(1,1),parentId int,childId int)
--insert A
--select 1,'aaa' union all
--select 2,'bbb' union all
--select 3,'ccc' union all
--select 4,'a1' union all
--select 5,'a2' union all
--select 6,'b1' union all
--select 7,'aa1' union all
--select 8,'dsdssd'
--insert B
--select 1,4 union all
--select 1,5 union all
--select 4,7 union all
--select 7,8
WITH cte
AS ( SELECT parentId ,
childId ,
1 [LEVEL] --定义级别为顶层
FROM b
WHERE parentid = 1
UNION ALL
SELECT b.parentid ,
b.childId ,
a.[level] + 1 --计算B中的个个级别
FROM cte a
INNER JOIN B ON B.parentid = a.childId
)