sql語句查詢下級下下級

2021-07-22 06:12:40 字數 1187 閱讀 5162

1.ms sql

with cte as

(select id,pid,deptname, 0 as lvl from department

where id = 2

union all

select d.id,d.pid,d.deptname,lvl + 1 from cte c inner join department d

on c.id = d.pid

)select * from cte

2.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

上下級查詢

create table catalog id int identity 1,1 primary key,name varchar 20 not null,superid int 上級id remark varchar 50 go insert into catalog values 所有類別 0,...

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

無限層級結構的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.fr...

PHP查詢該使用者的無限下級

php 1.整個會員表的資料 agentid代表 父級id member array array id 1,agentid 0,nickname a array id 2,agentid 1,nickname b array id 3,agentid 2,nickname c array id 4,...