2016-07-05 15 views
1

Ich habe zwei Tabelle eines Speichern von Daten und übergeordnete Hierarchie und andere Pfade und NachkommeSumme Preis von Childs in anderer Tabelle mysql

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

Ich brauche all Benutzer-ID mit den Eltern bekommen 1 dann Nachkommen in anderem Tisch bekommen und Gruppe von Benutzer-ID Summe Preise

+-------------+---------------+-------------+ 
| 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 | 
+-------------+---------------+-------------+ 

ich habe es alle childs zusammen, um dieses

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 

Abfrage summieren funktionieren aber Gesamtsumme Mutter 1

ich unten Ergebnis für Kind direkt (2,3)

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

auch in erstellen sqlfiddle meine Frage http://sqlfiddle.com/#!9/9415ed/2

Antwort

0

Versuchen Sie dies;)

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

Herausgegeben

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

+0

funktioniert gut, verwenden Sie IN Geschwindigkeit nicht verringern? –

+0

@VahidAlvandi OK, lass uns 'JOIN' verwenden, überprüfe meine *** bearbeitete *** Antwort bitte. – Blank

+0

funktionieren gut, ich brauche ein Buch für Tutorial mysql wie Sie .. bitte stellen Sie sich selbst –

-1

versuchen, diese

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 
zeigen müssen
+0

Ihre Antwort nicht. danke –