uid 用户ID, mycode 我的邀请码, pcode 我的上级邀请码, rflag 已认证。
表结构如图所示,请问如何通过SQL语句或者自定义函数查询出子节点及其子节点的子节点。
例如 uid为1的用户,邀请了2和3,2和3继续邀请。
那么我统计u1时,查询结果为8(排除自己)。如何实现?

解决方案 »

  1.   

    https://dev.mysql.com/doc/refman/8.0/en/with.html
      

  2.   

    这个是自连接
    首先建临时表--取几级关联几次
    create table table_2 as 
    select
    t.uid,
    count(distinct t1.uid) u_cnt_1,  --一级
    count(distinct t2.uid) u_cnt_2   --二级
    from 
    (select uid,mycode,p_code from table) t
    left join
    (select uid,mycode,p_code from table) t1
    on t.mycode=t1.p_code
    left join 
    (select uid,mycode,p_code from table) t2
    on t1.mycode=t2.p_code
    ;然后将所需要的到几级的人数加在一起select 
    uid,
    u_cnt_1+u_cnt_2
    from table_2;
      

  3.   

    楼主你好,可以用递归的方法来实现,代码如下CREATE DEFINER=`root`@`%` PROCEDURE `Proc_GetMySub`(IN `InUid` int)
    label_pro:BEGIN
    DECLARE userCode int DEFAULT 0;

    SELECT mycode into userCode FROM tb_xx; -- 建一个临时表
    DROP TABLE IF EXISTS tbTem_userId;
    create table tbTem_userId(uid INT);

    -- 我的第一下级
    INSERT INTO tbTem_userId SELECT uid FROM tb_xx WHERE pcode = userCode;
    -- 我的第二下级
    INSERT INTO tbTem_userId SELECT uid FROM tb_xx WHERE pcode IN (SELECT uid FROM tb_xx WHERE pcode = userCode);

    -- 查询出所有的下级
    SELECT uid FROM tbTem_userId;
    END
    如果要查询多个下级一次类推,不过不建议下级超过5级,即使用其他的递归查询也是效率极低,如果非要用多级的话建议楼主根据应用场景重新设计表以便达到较好的查询效率