mysql根据父级编码得到父级内容_在mysql查询中按父获取所有子级

bd96500e110b49cbb3cd949968f18be7.png

I have a table with userid, managerid as follows:

id manager

------- -------

admin (NULL)

james admin

user james

workad user

creator workad

Now I want all the children (descendants) for one user id. In other words, for the userid james i need the children user, workad, creator. Because james is the top parent (ancestor). Is there any query to fetch result like this in mysql... Thanks in advance.

解决方案

For that you need to have a stored function :

DELIMITER $$

DROP FUNCTION IF EXISTS `junk`.`GetFamilyTree` $$

CREATE FUNCTION `GetFamilyTree` (GivenID VARCHAR(1024)) RETURNS varchar(1024) CHARSET latin1

DETERMINISTIC

BEGIN

DECLARE rv,q,queue,queue_children,front_id VARCHAR(1024);

DECLARE queue_length,pos INT;

SET rv = '';

SET queue = GivenID;

SET queue_length = 1;

WHILE queue_length > 0 DO

SET front_id = queue;

IF queue_length = 1 THEN

SET queue = '';

ELSE

SET pos = LOCATE(',',queue) + 1;

SET q = SUBSTR(queue,pos);

SET queue = q;

END IF;

SET queue_length = queue_length - 1;

SELECT IFNULL(qc,'') INTO queue_children

FROM (SELECT GROUP_CONCAT(id) qc

FROM Table1 WHERE manager = front_id) A;

IF LENGTH(queue_children) = 0 THEN

IF LENGTH(queue) = 0 THEN

SET queue_length = 0;

END IF;

ELSE

IF LENGTH(rv) = 0 THEN

SET rv = queue_children;

ELSE

SET rv = CONCAT(rv,',',queue_children);

END IF;

IF LENGTH(queue) = 0 THEN

SET queue = queue_children;

ELSE

SET queue = CONCAT(queue,',',queue_children);

END IF;

SET queue_length = LENGTH(queue) - LENGTH(REPLACE(queue,',','')) + 1;

END IF;

END WHILE;

RETURN rv;

END $$

Then you can call like :

SELECT `id`, `manager`,GetFamilyTree(`id`) as children

from Table1;

You can have filters as well:

SELECT `id`, `manager`,GetFamilyTree(`id`) as children

from Table1 where `id` = 'james';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值