dimanche 19 juin 2016

get minimum from result with group by mysql

i have table it store hierarchy data in mysql this table store stable relation but if each user les than 1000 buy removed and user User a lower level replace thia is my code and work fine, after qroup by it contain all ancestor of descendant with compare then COUNT(*) AS level count level each user, this i have sql code to compress data According to minimum buy for each user

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

this is table buy

+--------+--------+
| userid | amount |
+--------+--------+
|      2 |   2000 |
|      4 |   6000 |
|      6 |   7000 |
|      1 |   7000 |

mysql code

 SELECT a.* 


FROM
    ( SELECT userid 
       FROM webineh_user_buys 
      GROUP BY userid
      HAVING SUM(amount) >= 1000
    ) AS buys_d 

JOIN
    webineh_prefix_nodes_paths AS a 
    ON a.descendant_id = buys_d.userid

 JOIN  
    (
        SELECT userid  
        FROM webineh_user_buys 
        GROUP BY userid
        HAVING SUM(amount) >= 1000
    ) AS buys_a on (a.ancestor_id = buys_a.userid )


  JOIN 
     ( SELECT descendant_id
            , MAX(path_length) path_length 
         FROM webineh_prefix_nodes_paths 
         where a.ancestor_id = ancestor_id
        GROUP
           BY descendant_id
     ) b
    ON b.descendant_id = a.descendant_id
   AND b.path_length = a.path_length



 GROUP BY a.descendant_id, a.ancestor_id 

i need get max path_length where ancestor_id have At least 1000 amount buy

but have error in where in subquery where a.ancestor_id = ancestor_id error code

1054 - Unknown column 'a.ancestor_id' in 'where clause'

i add sqlfidle demo

Aucun commentaire:

Enregistrer un commentaire