在父子层次结构中查找最多7级的级别段

uinbv5nw  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(412)

父子表
IDontroducer\u idname1nullriya21ramesh31anand42prety53rakesh
当id=1时查询以获取成员列表

select  id AS memberid, name 
from (select * 
      from table_member 
      order by introducer_id, id) table_member_sorted,
     (select @pv := '1') initialisation 
where find_in_set(introducer_id, @pv) 
  and length(@pv := concat(@pv, ',', id))

上面的查询显示输出
会员机构名称
现在我还想找到所有成员的级别(即,我希望输出为:
成员ID名称级别2修订13 ANAND 14 PREETY25 RAKESH2
如何更新以前的查询以获得上述输出?
注:查询显示最高级别7
谢谢您。

wribegjk

wribegjk1#

CREATE PROCEDURE get_tree (start_from INT)
BEGIN
    DROP TABLE IF EXISTS tmp;
    CREATE TABLE tmp (member_id INT PRIMARY KEY, 
                      name VARCHAR(255),
                      level INT);
    INSERT INTO tmp SELECT id, name, 0
                    FROM test
                    WHERE id = start_from;
    REPEAT
        INSERT IGNORE INTO tmp SELECT test.id, test.name, tmp.level + 1
                               FROM test
                               JOIN tmp ON tmp.member_id = test.introducer_id;
    UNTIL !ROW_COUNT() END REPEAT;
    SELECT * FROM tmp;
END

小提琴
我已经分享了我的sql版本的截图链接。snipboard.io/qbdb0a.jpg–屏幕
您的sql server版本是10.4.14秋叶树
供您的服务器版本使用

WITH RECURSIVE
cte AS ( SELECT id member_id, name, 0 level
         FROM test
         WHERE id = @start_from 
       UNION ALL
         SELECT test.id, test.name, cte.level + 1
         FROM test
         JOIN cte ON cte.member_id = test.introducer_id 
      -- WHERE cte.level < 7 )
SELECT * 
FROM cte;

小提琴

相关问题