其他表mysql

时间:2016-07-05 17:45:48

标签: mysql sql join group-by sum

我有两个表一个商店数据子级和父级层次结构以及其他路径和后代

+----------+------------+-----------+
| userid   |    parent  |    price  |
+----------+------------+------------
| 1        |    null    |      20   | 
| 2        |      1     |      20   | 
| 3        |      1     |      20   | 
| 4        |      2     |      20   | 
| 5        |      2     |      20   | 
| 6        |      3     |      20   | 
| 7        |      4     |      20   | 
+----------+------------+-----------+

我需要使用父级1获取所有用户ID,然后通过用户ID和价格获得其他表和组中的后代

+-------------+---------------+-------------+
| ancestor_id | descendant_id | path_length |
+-------------+---------------+-------------+
|           1 |             1 |           0 |
|           1 |             2 |           1 |
|           1 |             3 |           1 |
|           1 |             4 |           2 |
|           1 |             5 |           2 |
|           1 |             6 |           2 |
|           1 |             7 |           3 |
|           2 |             2 |           0 |
|           2 |             4 |           1 |
|           2 |             5 |           1 |
|           2 |             7 |           2 |
|           3 |             3 |           0 |
|           3 |             6 |           1 |
|           4 |             4 |           0 |
|           4 |             7 |           1 |
|           5 |             5 |           0 |
|           6 |             6 |           0 |
|           7 |             7 |           0 |
+-------------+---------------+-------------+

我已经查询了所有孩子的总和

select 
sum(b.price)

from webineh_prefix_nodes_paths_tmp a

    join webineh_prefix_nodes_tmp b on (b.userid = a.descendant_id)

where a.ancestor_id = 1 

这项工作很好,但总和父1

我需要直接显示儿童直接结果(2,3)

 +----------+------------+-
    | userid   |    total   |
    +----------+------------+
    | 2        |    80      |
    | 3        |    40      |
    +----------+------------+

也在创建sqlfiddle我的问题http://sqlfiddle.com/#!9/9415ed/2

2 个答案:

答案 0 :(得分:0)

试试这个;)

select ancestor_id as userid, sum(b.price) as total
from webineh_prefix_nodes_paths_tmp a 
join webineh_prefix_nodes_tmp b 
on b.userid = a.descendant_id
where a.ancestor_id in (select userid from webineh_prefix_nodes_tmp where parent = 1)
group by ancestor_id

SQLFiddle Demo

<强> 被修改

select ancestor_id as userid, sum(b.price) as total
from webineh_prefix_nodes_paths_tmp a 
join webineh_prefix_nodes_tmp b 
on b.userid = a.descendant_id
inner join webineh_prefix_nodes_tmp c
on a.ancestor_id = c.userid
and c.parent = 1
group by ancestor_id

SQLFiddle Demo

答案 1 :(得分:-1)

试试这个

select sum(b.price) from webineh_prefix_nodes_paths_tmp a join webineh_prefix_nodes_tmp b on (b.userid = a.descendant_id) where a.ancestor_id in ( 1,2,3) GROUP by ancestor_id