資料庫遞迴查詢(CET)

2021-09-06 12:45:50 字數 3829 閱讀 4199

if object_id('[ta]')isnotnull

droptable[ta]

go

createtableta([id]int,[name] nvarchar(4),[parentid] nvarchar(2))

go

insertintota

select1,'河北省','0'unionall

select2,'邢台市','1'unionall

select3,'石家莊市','1'unionall

select4,'張家口市','1'unionall

select5,'南宮','2'unionall

select6,'壩上','4'unionall

select7,'任縣','2'unionall

select8,'清河','2'unionall

select9,'河南省','0'unionall

select10,'新鄉市','9'unionall

select11,'aaa','10'unionall

select12,'bbb','10'

go

--start

;withdistrict

as

(select*fromtawhere[name]=n'河北省'

unionall

selecta.*fromta a,district bwherea.parentid=b.id

)

select*fromdistrict

--result:

/*

idnameparentid

----------- ---- --------

1           河北省  0

2           邢台市  1

3           石家莊市 1

4           張家口市 1

6           壩上   4

5           南宮   2

7           任縣   2

8           清河   2

*/

上面**可以還不夠清晰 給多乙個例子

with district

--查詢列

(pid, fdepartmentname,fstate, ffathername) as

--父表

(select  pid, fdepartmentname,fstate,convert(nvarchar(50), '') as ffathername from dbo.t_department where   (fparentuserid is null or fparentuserid=0)

union all

--子表(注意是b的fdepartmentname)

select a.pid, a.fdepartmentname,a.fstate,b.fdepartmentname as ffathername from dbo.t_department as a

--關係

inner join district as b on a.fparentuserid = b.pid)

--查詢

select   pid, fdepartmentname,fstate, ffathername

from      district as c

資料庫遞迴查詢

今天工作看同事 用到了start with.connect by prior,不知道什麼意思,查詢了一些資料,以下是比較好理解的。oracle中的select語句可以用start with.connect by prior子句實現遞迴查詢,connect by 是結構化查詢中用到的,其基本語法是 s...

關於資料庫的遞迴查詢

1 oracle 以scott.emp表舉例 empno是人員編號,mgr是上級領導 也就是上級人員編碼 1 從上到下查詢 該查詢查詢員工jones下屬所有的員工 select emp.from emp start with ename jones connect by mgr prior empn...

遞迴查詢資料庫分銷上級

太陽線為準 團隊中所有的uid 一般情況最多10個 關於向上去找,還是向下去找,這裡取個巧 先比較下他們的uid大小,uid大的一定是後面註冊上來的 所以,以uid為大的來向上查詢 public function team tree uid,level 1 this team tree parent...