mor*_*di3 6 mysql database hierarchy
我需要为注册到网站的用户提供5级层次结构.每个用户都被另一个用户邀请,我需要知道用户的所有后代.也是用户的祖先.
我想到了2个解决方案.
ancestor_id descendant_id distance
1 1 0
2 2 0
3 3 0
4 4 0
5 5 0
6 6 0
2 3 1
Run Code Online (Sandbox Code Playgroud)
user_id ancestor_level1_id ancestor_level2_id ancestor_level3_id ancestor_level4_id ancestor_level5_id
10 9 7 4 3 2
9 7 4 3 2 1
Run Code Online (Sandbox Code Playgroud)
这些好主意吗?
我知道"邻接列表模型"和"修改后的预订树遍历算法",但这些是"推荐"系统的良好解决方案吗?
我需要在这棵树上执行的查询是:
ancestor_id descendant_id distance
1 1 0
2 2 0
3 3 0
4 4 0
5 5 0
6 6 0
2 3 1
Run Code Online (Sandbox Code Playgroud)
添加用户3引用的用户10.(我认为您不需要在这两个插入之间锁定表):
insert into ancestor_table
select ancestor_id, 10, distance+1
from ancestor_table
where descendant_id=3;
insert into ancestor_table values (10,10,0);
Run Code Online (Sandbox Code Playgroud)
查找用户3引用的所有用户.
select descendant_id from ancestor_table where ancestor_id=3;
Run Code Online (Sandbox Code Playgroud)
要按深度计算这些用户:
select distance, count(*) from ancestor_table where ancestor_id=3 group by distance;
Run Code Online (Sandbox Code Playgroud)
找到用户10的祖先.
select ancestor_id, distance from ancestor_table where descendant_id=10;
Run Code Online (Sandbox Code Playgroud)
此方法的缺点是此表将占用的存储空间量.
| 归档时间: |
|
| 查看次数: |
2251 次 |
| 最近记录: |