How to calculate the sum of values in a tree using SQL

后端 未结 9 2541
耶瑟儿~
耶瑟儿~ 2021-01-05 09:29

I need to sum points on each level earned by a tree of users. Level 1 is the sum of users\' points of the users 1 level below the user. Level 2 is the Level 1 points of the

9条回答
  •  忘掉有多难
    2021-01-05 09:56

    Trees don't work well with SQL. If you have very (very very) few write accesses, you could change the tree implementation to use nested sets, that would make this query incredibly easy.

    Example (if I'm not mistaken):

    SELECT SUM(points) 
    FROM users 
    where left > x and right < y 
    

    However, any changes on the tree require touching a massive amount of rows. It's probably better to just do the recursion in you client.

提交回复
热议问题