如何使用 mysql 查询 select 下线用户?

How to select downline users using mysql query?

我想select下线用户反对一个用户id。

这是我的 table 结构:

"userid", "sponsorID", "username"

而进入table的数据是:

1, 0, noman
2, 1, jani
3, 2, usman
4, 3, hassan
5, 4, ahmad
6, 5, haroon
7, 1, sabir

我想要这样的数据:

"Select * from table where sponsorID = 1

这应该select所有下线用户,意味着它应该首先select用户2,然后它也会select用户3,因为用户2是由用户1赞助的并且用户 3 由用户 2 赞助,并且将 select 整个下线与这种情况。

我试过:

select * from table where sponsorID = '1'

但是select只有一个用户,我想要整个下线用户的数据。

我不知道如何在 mysql 中进行查询以获得所需的数据。如果有人知道请举个例子。

如果你是运行 MySQL 8.0,可以用递归查询解决:

with recursive cte as (
    select userid, sponsorid, username, 1 lvl from mytable where sponsorid = 1
    union all
    select t.user, t.sponsorid, t.username, c.lvl + 1
    from cte c
    inner join mytable t on t.sponsorid = c.userid
)
select * from cte

递归查询的锚点选择用户1赞助的所有用户。然后,递归部分按照关系,选择之前选择的用户赞助的所有用户,直到树耗尽。

作为奖励,我添加了 lvl 列,它表示树中每个节点的深度。

请注意,这假定树中没有循环引用。