需求:
在樹形的節點關係下,比如選單樹或者檔案目錄樹,要想獲取某個節點的所有子節點,或者所有父類節點,在知道節點樹最大層級的情況下,可以直接通過一條sql直接查詢實現
表結構:
id, parent_id
eg: 已知節點樹深度不超過10, 查詢id=100010的節點的所有子節點
select
org.id as id,
concat(
'[',
concat_ws(',',
group_concat( distinct pa1.id ),
group_concat( distinct pa2.id ),
group_concat( distinct pa3.id ),
group_concat( distinct pa4.id ),
group_concat( distinct pa5.id ),
group_concat( distinct pa6.id ),
group_concat( distinct pa7.id ),
group_concat( distinct pa8.id ),
group_concat( distinct pa9.id ),
group_concat( distinct pa10.id ) ),
']'
) as child_ids
from organization org
left join organization pa1 on org.id=pa1.parent_id
left join organization pa2 on pa1.id=pa2.parent_id
left join organization pa3 on pa2.id=pa3.parent_id
left join organization pa4 on pa3.id=pa4.parent_id
left join organization pa5 on pa4.id=pa5.parent_id
left join organization pa6 on pa5.id=pa6.parent_id
left join organization pa7 on pa6.id=pa7.parent_id
left join organization pa8 on pa7.id=pa8.parent_id
left join organization pa9 on pa8.id=pa9.parent_id
left join organization pa10 on pa9.id=pa10.parent_id
where org.id=100010
group by org.id;
結果:
id, child_ids
100, [1,2,3,4]
已知節點樹深度不超過10, 查詢id=100038的節點的所有父節點
select
org.id,
concat(
'[',
concat_ws(',',
zo.parent_id,
pa1.parent_id,
pa2.parent_id,
pa3.parent_id,
pa4.parent_id,
pa5.parent_id,
pa6.parent_id,
pa7.parent_id,
pa8.parent_id,
pa9.parent_id,
pa10.parent_id ),
']'
) as parent_ids
from organization org
left join organization pa1 on pa1.id=org.parent_id
left join organization pa2 on pa2.id=pa1.parent_id
left join organization pa3 on pa3.id=pa2.parent_id
left join organization pa4 on pa4.id=pa3.parent_id
left join organization pa5 on pa5.id=pa4.parent_id
left join organization pa6 on pa6.id=pa5.parent_id
left join organization pa7 on pa7.id=pa6.parent_id
left join organization pa8 on pa8.id=pa7.parent_id
left join organization pa9 on pa9.id=pa8.parent_id
left join organization pa10 on pa10.id=pa9.parent_id
where org.id=100038
結果:
id, parent_ids
100, [1,2,3,4]
注group_concat(field_name separator 『,』) 分組合併某列, 即將分組後每組資料的某列合併為一行資料(多行資料合併為一行,只針對一列)
group_concat()中的值為你要合併的資料的欄位名;
separator 函式是用來分隔這些要合併的資料的;
』 '中是你要用哪個符號來分隔,預設使用 ','分隔;
注:group_concat只有與group by語句同時使用才能產生效果,需要將拼接的結果去重的話,可與distinct結合使用即可。
MySQL遞迴查詢所有子節點,樹形結構查詢
delimiter drop procedure if exists findlchild iid 遞迴父節點 layer 允許遞迴深度 create procedure findlchild iid bigint 20 layer bigint 20 begin 建立接受查詢的臨時表 create...
Mysql 遞迴查詢子節點
查詢父編碼及以下所有子節點 select id from select t1.id,t1.parent id,if find in set t1.id,pids 0,pids,if find in set t1.parent id,pids 0,pids concat ws pids,id 0 as...
bom結構,查詢節點下所有子節點
bom結構,查詢節點下所有子節點 create table os id int,parentid int,desn varchar 10 insert into os select 1,0,體育用品 insert into os select 2,0,戶外運動 insert into os sele...