i have 2 table one store data of relation user other buy user
path table
+-------------+---------------+-------------+
| ancestor_id | descendant_id | lenght |
+-------------+---------------+-------------+
| 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 |
algoritm =
1- select and group buy for each user at last 1000 for descendant
2- join to path table with descendant_id = result step1
3- again select and group buy for each user at last 1000 for ancestor
4- must get min path_length Except zero According to join in step 2 with ancestor have at last 1000 , aslo if just have one path_length set to null
this mysql code i need a where compare path_length with have ancestor
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
Intended result
+--------+--------++--------++------
| descendant | ancestor | path_length
+--------+--------++--------++-------
| 1 | null | null
| 2 | 1 | 1
| 4 | 2 | 1
| 6 | 4 | 2
but have error please see sqlfidle
Unknown column 'a.ancestor_id' in 'where clause'
Best Answer
Try this