直接看sql
begin
declare childs longtext;
declare tempchildids longtext;
declare tempparentids longtext;
declare otempc int(11);
set childs = '';
set tempchildids='';
set tempparentids=concat(pid,'');
set otempc = 0;
while tempparentids is not null and tempparentids !=''
do
set otempc =otempc+1;
set childs = concat(childs,if(tempchildids='','',concat(',',tempchildids)));
select group_concat(concat(id,'-',otempc)),group_concat(id) into tempchildids,tempparentids from m_member where parent_id is not null and find_in_set(parent_id,tempparentids);
end while;
return childs;
end
其中pid为最顶层用户id,作为函数参数。运行结果如下:
结果的结构为 用户id-层级,再执行程序运算时可以逗号‘,’劈开为数组进行遍历,再以’-‘进行分割,就可以算出所有下级及所处层级。
如果是在MySQL 中 可以利用FIND_IN_SET()函数去匹配用户id做关联查询条件,如下
#注意substr(结果,2)去除前面逗号,再将 ’-‘替换为’,-‘,最终为 4,-1,39,-1
#在id关联匹配时则只有 4 39 会关联到,层级的 -1或 -5不会关联,只要数据id不为-1、-5这样的就没问题
FIND_IN_SET(user_id,replace(substr(getallchilds(8),2),'-',',-'))
在这里记录,分享一下,以便以后查看。