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

Find the level segments up-to 7-levels in parent-child hierarchy

亲子table

id introducer_id name
1 NULL Riya
2 1 Ramesh
3 1 Anand
4 2 Preety
5 3 Rakesh

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))

以上查询显示输出

member_id name
2 Ramesh
3 Anand
4 Preety
5 Rakesh

现在我也想知道所有成员的等级 (即)我希望输出为:

member_id name level
2 Ramesh 1
3 Anand 1
4 Preety 2
5 Rakesh 2

如何更新我以前的查询以获得上述输出?

注:查询最多显示7级

谢谢。

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

fiddle


I have shared screenshot link of my sql version. snipboard.io/qbdB0A.jpg – AfreenB

Your SQL server version is MariaDB 10.4.14. – Akina

对于您的服务器版本使用

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;

fiddle