SQL語句遞迴查詢

2022-02-05 08:32:52 字數 1304 閱讀 1371

通過sql語句遞迴查詢所有下級或上級使用者

1.ms sql

with

cte as(

select

id,pid,deptname,0as

lvl

from

department

where

id =

2union

allselect

d.id,d.pid,d.deptname,lvl+1

from

cte c

inner

join

department d

onc.id

=d.pid

)select

*from

cte2.oracle

一、建表

create table users.tbl_test

id    number,

name  varchar2(100 byte),

pid   number                                  default 0

insert into tbl_test(id,name,pid) values('1','10','0');

insert into tbl_test(id,name,pid) values('2','11','1'

insert into tbl_test(id,name,pid) values('3','20','0');

insert into tbl_test(id,name,pid) values('4','12','1');

insert into tbl_test(id,name,pid) values('5','121','2');

二、格式

select * from …. where [結果過濾條件語句]

start with  [and起始條件過濾語句]

connect by prior [and中間記錄過濾條件語句]

三、查詢所有下級

select * from tbl_test start with id=1 connect by prior id=pid

注意:此sql能查詢id=1的資料的所有下級,寫sql語句時要注意,因為是從id開始查詢下級,所以connect by prior 子句的條件是id=pid

四、查詢所有上級

select * from tbl_test start with id=5 connect by prior pid=id

因為是從id開始查詢上級,所以connect by prior 子句的條件是pid=d

sql語句遞迴查詢

表結構 給出乙個結點找到該節點的所有 子 節點 with c depts as select dept.from department dept where dept.pptr 父節點id union all select dept.from c depts department dept wher...

SQL語句遞迴查詢

通過sql語句遞迴查詢所有下級或上級使用者 1.ms sql with cte as select id,pid,deptname,0as lvl from department where id 2union allselect d.id,d.pid,d.deptname,lvl 1 from c...

sql語句遞迴查詢(start with)

在做專案中遇到乙個問題,就是同乙個表中的資料存在級聯關係,但是只要查出來的末級資料,糾結了好久,好不容易找到了乙個博主的分享,在這裡做個記錄,也是和大家一起分享學習一下這位大神的技術,共勉 寫 時碰到要弄清楚oracle的role之間的傳遞關係,就是有role a的話,可以通過grant a to ...