工作中用到了一个场景、根据某个节点查询全部子集、一开始用的网上千篇一律的sql方式、但是在测试环境只能遍历三层、第四层开始就查询不出来、于是转换思路用函数方式
上函数
CREATE DEFINER=`root`@`%` FUNCTION `getChild`(in_id varchar(32)) RETURNS varchar(1000) CHARSET utf8
begin
declare ids varchar(1000) default '';
declare tempids varchar(1000);
set tempids = in_id;
while tempids is not null do
set ids = CONCAT_WS(',',ids,tempids);
select GROUP_CONCAT(id) into tempids from catalogue where FIND_IN_SET(pid,tempids)>0;
end while;
return ids;
end
说明:
表设计要有父Id这种标识字段
1、方法名:getChild()、可根据自己需要换成自己想起的方法名
2、参数是根节点的id
2、catalogue 是表明 替换成自己的表名
3、pid 是我表中的父id、可根据实际业务场景替换
4、函数创建完直接调用函数就行了
开始调用
select * from catalogue where FIND_IN_SET(id,getChild('1643804308886073346'))
结果:
240711补充一种方式
select * from (
select id,pid,level,ding_dept_name from po_ding_dept where id = 550954856
union
select t.id,t.pid,t.level,t.ding_dept_name from (select * from po_ding_dept where pid is not null) t,
(select @pid := 550954856) pd
where FIND_IN_SET(pid,@pid) > 0
and @pid := CONCAT(@pid,',',id)
) as bbbb
order by bbbb.level asc