'MySQL tree structure query and joining a other table

I need some help with a MySQL / MariaDB query. I have two tables, a user table and a reward table.

user table, storage for users who can referral other users. By doing so, they are getting rewarded.

reward table, storage / history for rewards. Rewards are based on level's, level 1 is getting more rewards then level 2, level 3 etc..

Now I would like to have a stored procedure that gives me the following result based on two values:

Input:

  1. root user Id
  2. max level of rewards

Output:

+------+-----------+----------+--------+
| id   | name      | rewards  | level  |
+------+-----------+----------+--------+
|    4 | parent 1  |       75 |      1 |
|    4 | parent 1  |        0 |      2 |
|    5 | parent 2  |        0 |      1 |
|    5 | parent 2  |        0 |      2 |
+------+-----------+----------+--------+

id --> user id name --> users name

rewards - level 1 --> total rewards that this referral has raised

rewards - level 2 --> total rewards that this referral has raised

rewards - level 3 --> ...

I already did some investigation and was thinking of a RCT (Rrecursive Common Table) for getting the user tree structure and joining the outcome on the rewards table. Writing the RCT isn't that difficult but iam getting stuck on joining the reward table. Do I have to use a CTE there too?

Any sugestions on the query as well on the database structure is welcome.

Please find the SQL fiddle here: https://www.db-fiddle.com/f/fXs5F6s62JyRn9hWBkc2pj/1



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source