So, I feel the need to be recorded, so that after the encounter this problem again, and get answers from the idea.
Problem: Find the SQL: retrieve all the leaf nodes under a node
Department table name: tb_department
the above mentioned id int - node of the above mentioned id
pid int - the parent node of the above mentioned id
Caption VARCHAR (50) - the department name
----------------------- --------------
the above mentioned id pid Caption
--------------------------------- -------------
1 0 AA
20 1 BB
64 20 CC
22 1 DD
23 22 The
24 1 FF
25 0 GG
26 1 HH
27 25 II
---------------- ---------------- tree follows
------------ --------------------------
Q: how to retrieve all of the most end of the leaf nodes under a node.
For example: to retrieve all the nodes under the tail end node AA CC, EE, FF, HH?
My solution for 2005 and above versions sql server:
-
create
table tb_department(
-
id
int,
--节点id
-
pid
int,
--父节点id
-
caption
varchar(
50)
--部门名称
-
)
-
-
insert
into tb_department
-
select
1 ,
0 ,
'AA'
union all
-
select
20 ,
1 ,
'BB'
union all
-
select
64 ,
20 ,
'CC'
union all
-
select
22 ,
1 ,
'DD'
union all
-
select
23 ,
22 ,
'EE'
union all
-
select
24 ,
1 ,
'FF'
union all
-
select
25 ,
0 ,
'GG'
union all
-
select
26 ,
1 ,
'HH'
union all
-
select
27 ,
25 ,
'II'
-
go
-
-
-
;with t
-
as
-
(
-
select
id,pid,caption
-
from tb_department
-
where caption =
'AA'
-
-
union all
-
-
select t1.id,t1.pid,t1.caption
-
from t
-
inner
join tb_department t1
-
on t.id = t1.pid
-
)
-
-
select *
-
from t
-
where
not
exists(
select
1
from tb_department t1
where t1.pid = t.id)
-
/*
-
id pid caption
-
24 1 FF
-
26 1 HH
-
23 22 EE
-
64 20 CC
-
*/
If it is sql server 2000, how to write it:
-
--1.建表
-
create
table tb_department(
-
id
int,
--节点id
-
pid
int,
--父节点id
-
caption
varchar(
50)
--部门名称
-
)
-
-
insert
into tb_department
-
select
1 ,
0 ,
'AA'
union all
-
select
20 ,
1 ,
'BB'
union all
-
select
64 ,
20 ,
'CC'
union all
-
select
22 ,
1 ,
'DD'
union all
-
select
23 ,
22 ,
'EE'
union all
-
select
24 ,
1 ,
'FF'
union all
-
select
25 ,
0 ,
'GG'
union all
-
select
26 ,
1 ,
'HH'
union all
-
select
27 ,
25 ,
'II'
-
go
-
-
-
--2.定义表变量
-
declare @tb
table
-
(
id
int,
--节点id
-
pid
int,
--父节点id
-
caption
varchar(
50),
--部门名称
-
level
int
--层级
-
)
-
-
-
--3.递归开始
-
insert
into @tb
-
select *,
1
as
level
-
from tb_department
-
where caption =
'AA'
-
-
-
--4.递归的过程
-
while @@ROWCOUNT >
0
-
begin
-
-
insert
into @tb
-
select t1.id,t1.pid,t1.caption,
level +
1
-
from @tb t
-
inner
join tb_department t1
-
on t.id = t1.pid
-
where
not
exists(
select
1
from @tb t2
-
where t.level < t2.level)
-
end
-
-
-
--5.最后查询
-
select *
-
from @tb t
-
where
not
exists(
select
1
from tb_department t1
where t1.pid = t.id)
-
/*
-
id pid caption level
-
24 1 FF 2
-
26 1 HH 2
-
64 20 CC 3
-
23 22 EE 3
-
*/