SQL查詢無限層級結構的所有下級,所有上級

2022-06-02 22:09:11 字數 1025 閱讀 4278

無限層級結構的table1表,id(主鍵),parentid(父級id)查詢某個id的所有下級或所有上級,使用with as,union all 查詢

1、查詢id為1所有的下級

with t

as(

select * from table1 where id=1

union all

select a.* from table1 a inner join t on a.parentid=t.id

) select * from t

2、查詢id為88所有的上級

with t

as(

select * from table1 where id=88

union all

select a.*

from table1 a inner join t on a.id=t.parentid

) select * from t

**於:

無限層級結構的table1表,id(主鍵),parentid(父級id)查詢某個id的所有下級或所有上級,使用with as,union all 查詢

1、查詢id為1所有的下級

with t

as(

select * from table1 where id=1

union all

select a.* from table1 a inner join t on a.parentid=t.id

) select * from t

2、查詢id為88所有的上級

with t

as(

select * from table1 where id=88

union all

select a.*

from table1 a inner join t on a.id=t.parentid

) select * from t

bom結構,查詢節點下所有子節點

bom結構,查詢節點下所有子節點 create table os id int,parentid int,desn varchar 10 insert into os select 1,0,體育用品 insert into os select 2,0,戶外運動 insert into os sele...

查詢所有上級部門的SQL

create table testdept deptid int identity 1,1 primary key,deptname varchar 16 superdept int insert into testdept deptname,superdept values 總經辦 0 inser...

無限極分類查詢所有子孫節點的改進演算法

在以前,遇到無限極分類返回乙個節點的所有子孫節點時,我都是用遞迴計算的,後來發現時間複雜度和空間複雜度都太高了,後來自己研究了一下改進了演算法.節點資料如下 鍵值對分別是自己對應父親節點 tree array 1 0,2 1,3 2,4 3,5 4,6 5,7 6,8 7,9 8,10 9,11 1...