項目中有用戶組表UserGroup以下:
其中PID表示當前組的上級組
表數據以下:
如今想查詢出頂級組[沒有上級組叫頂級組]A1組的全部子孫組ID,SQL以下:
[sql] www.2cto.com
--查詢子節點
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
www.2cto.com
查詢結果以下:
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以下:
[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
) www.2cto.com
select * from RTU2
查詢結果以下:
id pid
----------- -----------
26 23
23 20
20 6
6 NULL
(4 行受影響)