I need to have a 5 levels hierarchy for the users registered to a website. Every user is invited by another, and I need to know all descendants for a user. And also ancestors for a user.
I have in mind 2 solution.
- Keeping a table with relationships this way. A closure table:
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
- Having this table for relationships. Keeping in a table 5 levels ancestors. A “ancestors” table:
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
Are these good ideas?
I know about “the adjacency list model” and “the modified preorder tree traversal algorithm”, but are these good solutions for a “referral” system?
The queries that I need to perform on this tree are:
- frequently adding a new users
- when a user buys something, their referrers get a percentage commission
- every user should be able to find out how many people they’ve referred (and how many people were referred by people who they referred….) at each level
Closure Table
To add user 10, referred by user 3. (I don’t think you need to lock the table between these two insertions):
To find all users referred by user 3.
To count those users by depth:
To find the ancestors of user 10.
The drawback to this method is amount of storage space this table will take.