mysql 遞迴查詢選單節點的所有子節點

2021-10-14 14:16:37 字數 1812 閱讀 6624

建立menu表:

create table `menu` (

`id` int(11) not null auto_increment comment '選單id',

`parent_id` int(11) default null comment '父節點id',

`menu_name` varchar(128) default null comment '選單名稱',

`menu_url` varchar(128) default '' comment '選單路徑',

`status` tinyint(3) default '1' comment '選單狀態 1-有效;0-無效',

primary key (`id`)

) engine=innodb auto_increment=1 default charset=utf8;

插入資料:

insert into `menu` values ('0', null, '選單0', ' ', '1');

insert into `menu` values ('1', '0', '選單1', '', '1');

insert into `menu` values ('11', '1', '選單11', '', '1');

insert into `menu` values ('12', '1', '選單12', '', '1');

insert into `menu` values ('13', '1', '選單13', '', '1');

insert into `menu` values ('111', '11', '選單111', '', '1');

insert into `menu` values ('121', '12', '選單121', '', '1');

insert into `menu` values ('122', '12', '選單122', '', '1');

insert into `menu` values ('1221', '122', '選單1221', '', '1');

insert into `menu` values ('1222', '122', '選單1222', '', '1');

insert into `menu` values ('12211', '1222', '選單12211', '', '1');

select id from (

select t1.id,

if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', id), 0) as ischild

from (

select id,parent_id from re_menu t where t.status = 1 order by parent_id, id

) t1,

(select @pids := 要查詢的選單節點 id) t2

) t3 where ischild != 0

if(express1,express2,express3)條件語句,if語句類似三目運算子,當exprss1成立時,執行express2,否則執行express3;

find_in_set(str,strlist),str 要查詢的字串,strlist 欄位名 引數以」,」分隔 如 (1,2,6,8),查詢字段(strlist)中包含(str)的結果,返回結果為null或記錄

如果parent_id 在@pid中,則將@pid 裡面再加上parent_id,按行依次執行

儲存過程實現方式:

mysql 遞迴查詢選單節點的所有子節點

背景 專案中遇到乙個需求,要求查處選單節點的所有節點,在網上查了一下,大多數的方法用到了儲存過程,由於線上環境不能隨便新增儲存過程,因此在這裡採用類似遞迴的方法對選單的所有子節點進行查詢。準備 建立menu表 create table menu id int 11 not null auto inc...

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

MySQL遞迴查詢父子節點

create table folder id bigint 20 not null,parent id bigint 20 default null,primary key id 建立函式 create function getparlist rootid bigint returns varcha...