mysql循环查询树状数据
完整function
CREATE FUNCTION `getChildList`(rootId BIGINT, table_name varchar(20)) RETURNS varchar(21845) CHARSET utf8 BEGIN DECLARE str VARCHAR(21845) ; DECLARE cid VARCHAR(21845) ; SET str = ''; SET cid =cast(rootId as CHAR); WHILE cid is not null DO SET str= concat(str,',',cid); IF table_name = 'tb_menu' THEN SELECT group_concat(id) INTO cid from tb_menu where FIND_IN_SET(p_id,cid)>0; ELSEIF table_name = 'tm_service_category' THEN SELECT group_concat(pk_id) INTO cid FROM tm_service_category where FIND_IN_SET(p_id,cid)>0; ELSEIF table_name = 'tm_part_category' THEN SELECT group_concat(pk_id) INTO cid FROM tm_part_category where is_del = 0 and FIND_IN_SET(p_id,cid)>0; end IF; END WHILE; RETURN str; END
mysql查询树解析(此处只是简单的循环并非递归):
例如:调用如下
select getChildList(0,tm_service_category)
提炼执行语句
WHILE cid is not null DO SET str= concat(str,',',cid); SELECT group_concat(pk_id) INTO cid FROM tm_service_category where FIND_IN_SET(p_id,cid)>0; END WHILE; RETURN str; END
tm_service_category 表结构如下
CREATE TABLE `tm_service_category` ( `pk_id` bigint(20) unsigned NOT NULL COMMENT '主键', `name` varchar(50) DEFAULT NULL COMMENT '名称', `p_id` bigint(20) unsigned DEFAULT NULL COMMENT '父节点', PRIMARY KEY (`pk_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
最主要的是p_id字段,表示父节点的pk_id
假设有数据如下
pk_id | p_id | name |
1 | 0 | a |
2 | 1 | b |
3 | 1 | c |
4 | 2 | d |
树结构如下:
整棵树的根节点为0,二级节点1,三级节点为2,3,四级节点为4
模拟执行循环语句
WHILE cid is not null DO SET str= concat(str,',',cid); SELECT group_concat(pk_id) INTO cid FROM tm_service_category where FIND_IN_SET(p_id,cid)>0; END WHILE; RETURN str; END
getChildList(0,tm_service_category)
1,初始化cid=0
2,查找p_id为0的所有节点拿到所有二级节点赋值给cid,cid=1,str=0,1
3,重复2步操作,查找p_id为1的所有节点拿到所有二级节点赋值给cid,cid=2,3,str=0,1,2,3
4,重复2步操作,查找p_id为2,3的所有节点拿到所有三级节点赋值给cid,cid=4,str=0,1,2,3,4
5,重复2步操作,查找p_id为4的所有节点赋值给cid,没找到任何节点,cid=null,退出循环