mysql樹形資料處理

2021-09-28 10:58:44 字數 2156 閱讀 7237

在實際開發中,會遇到類似部門一樣的樹形資料的處理,即部門巢狀。主要是兩個方面,獲取某個部門的絕對路徑(普元資訊/企業交付部/研發部/張三),以及獲取到某個部門下所有的子部門資訊(獲取到的子部門id用,號拼接顯示)。

group_concat函式:列轉行函式,將查詢出來的多個列的內容拼接成一行,並以,號分割。

find_in_set函式:find_in_set(str1,str2),該函式用於判斷str1是否存在於str2中,如果存在返回真,否則返回假。str中的多個字串用,號分隔

給出指定的部門id,獲取其父部門及祖先部門等,最後以/分割,例子如下:

亞信科技/研發部/研發一組/李四。如果要在其他語言中,做到這樣並不難,乙個迴圈,加字串拼接,最後返回字串就行了。但在mysql中(個人不是太熟悉mysql函式)還是覺得麻煩很多,附函式**如下:

begin

declare sparentlist varchar

(1000);

declare sparenttemp varchar

(1000);

declare snametemp varchar

(1000);

declare sidtemp varchar

(1000);

set sparenttemp = cast(rootid as

char);

while sparenttemp is

notnull

doif

(sparentlist is

notnull

)then

set sparentlist = concat(snametemp,

'/',sparentlist)

;else

set sparentlist = concat(snametemp)

;endif;

set sidtemp = sparenttemp;

select group_concat(parentid)

into sparenttemp from uump_organization where find_in_set(id,sparenttemp)

>0;

select group_concat(name)

into snametemp from uump_organization where find_in_set(id,sidtemp)

>0;

endwhile

;return sparentlist;

end

也是借助mysql函式,使用迴圈的方法,根據id以及parentid,將其name查出,最後拼接在sparentlist中然後返回。**需要理解下,在這裡不做過多的描述。

給定部門id,獲取其所有的子部門id,並以,號拼接。因為某個部門下的子部門很可能會有很多,還好mysql有自帶的group_concat函式,否則處理起來會麻煩很多。附**如下:

begin

declare stemp varchar

(1000);

declare stempchd varchar

(1000);

set stemp =

'$';

set stempchd =cast(rootid as

char);

while stempchd is

notnull

doset stemp = concat(stemp,

',',stempchd)

;select group_concat(id)

into stempchd from uump_organization where find_in_set(parentid,stempchd)

>0;

endwhile

;return stemp;

end

Vue樹形資料處理 js

當前需求 層級列表中選中某個元素,則獲取最底層子集id,並用逗號連線 1,2,3,4,5 let data 遍歷方法可參考 寫的很詳細 具體操作 首先找到選擇元素的id在樹形資料中的位置,並獲取他 findsameid tree,id if id tree i id isget deepsearch...

樹形結構資料處理

前端使用 構造樹型結構資料 param data 資料來源 param depid 兒子節點id欄位 預設 depid param parentid 父節點id欄位 預設 parentid param children 孩子節點資料儲存字段 預設 children param rootid 根id ...

樹形資料轉換

測試資料 create table project id int,name nvarchar 20 parent id int insert project select 1,所有專案 null union all select 2,專案1 1 union all select 3,專案2 1 cr...