dimanche 19 juin 2016

get minimum form one table with 2 join

i have bellow table it store hierarchy data

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

green circle have buy, we remove 5,1,3 but dont have buye but i dont now get minimum path_length form table above for each user

i have sql code to compress data According to minimum buy for each user

 SELECT
    buys_d.userid as descendant , 
    COUNT(*) AS level
FROM
    ( SELECT userid 
       FROM webineh_user_buys 
      GROUP BY userid
      HAVING SUM(amount) >= 1000
    ) AS buys_d 
  JOIN
    webineh_prefix_nodes_paths AS users 
      ON  users.descendant_id = buys_d.userid and users.ancestor_id != 1
  JOIN
    ( SELECT userid  

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

    ) AS buys_a
      ON  users.ancestor_id = buys_a.userid 


    GROUP BY
        buys_d.userid 

bellow is table buy

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

i need to get minimum path_length with equal to ancestor_id have buy more than 1000$ enter image description here

above picture show the ancestor ids have buy more 1000$ and userid 6 is descendant of 4 , 2

descendant | parent  |   level
2          |   1     |     1
4          |   2     |     2
6          |   4     |     3

i need to show parent column

Aucun commentaire:

Enregistrer un commentaire