我想根据用户ID选择下线用户。
这是我的表结构:
"userid", "sponsorID", "username"
并且表中的数据是:
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
这应该选择下线的所有用户,这意味着它应该首先选择用户2,然后也将选择用户3,因为用户2由用户1赞助,用户3由用户2赞助,并且在这种情况下将选择整个下线。
我尝试过:
select * from table where sponsorID = '1'
但是它只选择一个用户,我希望整个下线用户都有数据。
我不知道如何在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
列,它表示树中每个节点的深度。
注意,这假定树中没有循环引用。