Home > Database > Mysql Tutorial > SQLSERVER 2005 递归查询

SQLSERVER 2005 递归查询

WBOY
Release: 2016-06-07 15:51:58
Original
1211 people have browsed it

项目中有用户组表UserGroup如下: 其中PID表示当前组的上级组 表数据如下: 现在想查询出顶级组[没有上级组叫顶级组]A1组的所有子孙组ID,SQL如下: --查询子节点with RTD1 as(select id ,pid from UserGroup),RTD2 as(select * from RTD1 where id=6union al

项目中有用户组表UserGroup如下:

SQLSERVER 2005 递归查询

其中PID表示当前组的上级组

表数据如下:

SQLSERVER 2005 递归查询

现在想查询出顶级组[没有上级组叫顶级组]A1组的所有子孙组ID,SQL如下:

--查询子节点
with 
	RTD1 as(
		select id ,pid from UserGroup
	),
	RTD2 as(
		select * from RTD1 where id=6
		union all
		select RTD1.* from RTD2 inner join RTD1 
		on RTD2.id=RTD1.PID
	)
select * from RTD2
Copy after login


查询结果如下:

id          pid
----------- -----------
6           NULL
17          6
18          6
20          6
21          20
22          20
23          20
24          20
29          20
25          23
26          23
28          26
27          25

(13 行受影响)

 

现在想查询出A1-B3-C3-D2组的所有上级组ID,SQL如下:

--查询父节点
with 
	RTU1 as(
		select id ,pid from UserGroup
	),
	RTU2 as(
		select * from RTU1 where id=26
		union all
		select RTU1.* from RTU2 inner join RTU1 
		--on myT2.id=myT.PID
		on RTU2.PID=RTU1.ID
	)
select * from RTU2
Copy after login


查询结果如下:

id          pid
----------- -----------
26          23
23          20
20          6
6           NULL

(4 行受影响)

 

 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template