存储分层数据(MySQL)用于推荐营销

mor*_*di3 6 mysql database hierarchy

我需要为注册到网站的用户提供5级层次结构.每个用户都被另一个用户邀请,我需要知道用户的所有后代.也是用户的祖先.

我想到了2个解决方案.

  1. 以这种方式保持关系表.关闭表:

    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)
  1. 有这个关系表.保持在一个表5级祖先.一个"祖先"表:

   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)

这些好主意吗?

我知道"邻接列表模型"和"修改后的预订树遍历算法",但这些是"推荐"系统的良好解决方案吗?

我需要在这棵树上执行的查询是:

  • 经常添加新用户
  • 当用户购买东西时,他们的推荐人获得百分比佣金
  • 每个用户都应该能够在每个级别找出他们推荐了多少人(以及他们推荐的人推荐了多少人)

Ken*_*oom 8

关闭表

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)

此方法的缺点是此表将占用的存储空间量.