MySQL中用函式方法獲取樹形結構節點的深度

2021-09-05 09:25:54 字數 2499 閱讀 8805

思路

學習了用mysql函式查詢乙個節點所有子節點,但是沒找著如何實現查詢節點的深度。但轉念一想,只要反向查出所有父節點不就好了嗎,因為節點與父節點總是一一對應的,所以只要查出父節點列表就等於得到了深度

表結構

create

table

`hospital_user`

(`id`

varchar(36

)not

null

comment

'id'

,`pid`

varchar(36

)default

null

comment

'父級id'

,`name`

varchar(36

)default

null

comment

'名稱'

,`position`

varchar(50

)default

null

comment

'職位',`

order

`tinyint(4

)default

null

comment

'序號'

,`gender`

char(1

)default

null

comment

'性別'

,primary

key(

`id`))

engine

=innodb

default

charset

=utf8mb4 collate

=utf8mb4_0900_ai_ci comment

='醫院人員表'

;

資料結構

函式

drop

function

ifexists

`test`

.`getparent`

;create

function

`test`

.`getparent`

(rootid varchar(36

))returns

varchar

(1000

)deterministic

begin

declare ptemp varchar

(1000);

declare ctemp varchar

(1000);

set ptemp =

'#';

set ctemp = rootid;

while ctemp is

notnull

doset ptemp = concat(ptemp,

',', ctemp)

;select group_concat(id)

into ctemp

from hospital_user

where id =

(select pid from hospital_user where find_in_set(id,ctemp)

>0)

;end

while

;return ptemp;

end;

呼叫

select

*from

`hospital_user`

where find_in_set(id,getparent(

'83075e36-04aa-11e9-b954-e43b77a5d743'))

;select

count(*

)from

`hospital_user`

where find_in_set(id,getparent(

'83075e36-04aa-11e9-b954-e43b77a5d743'))

;select

*from

`hospital_user`

where find_in_set(id,getchild(

'83075e36-04aa-11e9-b954-e43b77a5d743'))

;

結果結果一:

結果二:

結果三:

第三個查詢是查詢子節點的,作為對比

在程式中用什麼方法獲取平台型別

在程式中用什麼方法獲取平台型別?環境產品 lotus domino designer 平台 無關 版本 6.x,7.x 問題在程式中用什麼方法獲取平台型別?解答在程式中可以通過 notessession類的 platform 屬性獲取當前的平台型別。樣例如下 dim session as new n...

MySQL中使用者授權 刪除授權的方法

使用者授權方法 你可以通過發出grant語句增加新使用者 如下 複製 shell mysql user root mysql mysql grant all privileges on to monty localhost identified by something with grant opt...

VC中用 函式 讀寫ini檔案的方法

vc中用函式讀寫ini檔案的方法 2007 05 31 15 23 ini檔案 即initialization file 這種型別的檔案中通常存放的是乙個程式的初始化資訊。ini檔案由若干個節 section 組成,每個section由若干鍵 key 組成,每個key可以賦相應的值。讀寫ini檔案實...