P_uid为邀请人,uid为用户,我邀请了三个人,这三个人又邀请了10个人,一直往下推,想输入一个邀请人ID就能知道下边有多少个用户
看下这里:https://blog.csdn.net/qq_34120430/article/details/84969235
就是递归调用,要自己做个函数实现,具体没环境你自己参考应该可以写得出
昨天看到有大佬cte递归案例还没学会,@一波大佬看看@DarkAthena
先说明下你的mysql版本吧,8之前和8之后的方法不一样
如果是8.0以上的话,使用with递归很容易实现
--测试数据
create table test_20220320_a (p_uid int,uid int);
insert into test_20220320_a value (null,2);
insert into test_20220320_a value (2,83);
insert into test_20220320_a value (2,84);
insert into test_20220320_a value (83,85);
insert into test_20220320_a value (83,87);
insert into test_20220320_a value (84,86);
insert into test_20220320_a value (84,88);
insert into test_20220320_a value (3,5);
--查询sql
with RECURSIVE cte as (
select p_uid, uid,uid root_uid from test_20220320_a where uid=2
union all
select a.p_uid,a.uid,cte.root_uid from test_20220320_a a,cte where a.p_uid=cte.uid
)
select count(p_uid),count(uid) from cte
上面这个sql就是在查询结果里增加了根节点的字段,这样就方便使用group by 聚合了