Answer the question
In order to leave comments, you need to log in
How to build a big tree that changes frequently?
Good afternoon experts.
In general, the question is this:
There is a large tree that changes steadily once a month. Now everything is implemented according to the Nested set model, because it is very easy to pull out the whole tree (and it is done often) without using recursion. But if you just need to pull out a tree - everything is simple. But this JOIN tree has data from other tables, and there is a lot of data (about 20-30 thousand rows).
To understand the issue, the application does the following: there is a structure of the sales department (structure), such as Region->City->Manager->Sales representative. Those. the tree is usually 5 to 7 levels. There is also a table of plans (plans), which stores monthly sales plans (structure_id, month, plan). And the sales table (sales) daily (structure_id, date, sale).
There is a request like:
SELECT
DISTINCT s1.id as id,
s1.name as name,
s1.left_key as left_key,
s1.right_key as right_key,
s1.level as level,
(SELECT s2.id FROM structure s2
WHERE s2.left_key < s1.left_key AND s2.right_key > s1.right_key
ORDER BY s2.right_key-s1.right_key ASC LIMIT 1) as parent,
(SELECT SUM(sum) FROM structure s3
JOIN sales r ON s3.id = r.structure_id
WHERE s3.left_key >= s1.left_key AND s3.right_key <= s1.right_key
AND r.date BETWEEN $startDate AND $endDate) as sum,
p.plan as plan
FROM structure s1
LEFT JOIN plans p ON s1.id = p.structure_id
AND p.month = $month
WHERE s1.left_key >= $leftKey AND s1.right_key <= $rightKey
ORDER BY s1.left_key ASC
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question