我有这个问题:
SELECT bi.id,
bi.location,
bi.expense_group,
bi.level,
bi.is_active,
bi.type,
full_name,
( bl.bud_amount ) AS BudgetAmount,
( COALESCE(( ( bl.bud_amount * 3 ) - (
+ bal.bal_amount1 + bal.bal_amount2
+ bal.bal_amount3 ) ), 0) ) AS Difference,
( COALESCE(Round(( + bal.bal_amount1 + bal.bal_amount2
+ bal.bal_amount3 ) / 3), 0) ) AS Average,
bal.bal_amount1 AS BAL1,
bal.bal_amount2 AS BAL2,
bal.bal_amount3 AS BAL3
FROM (SELECT *
FROM budget_items bi
WHERE bi.location IS NOT NULL) AS bi
LEFT JOIN (SELECT budget_item_id,
Sum(CASE
WHEN budget_id = 21491 THEN amount
END) AS bud_amount
FROM budget_lines
GROUP BY budget_item_id) AS bl
ON bl.budget_item_id = bi.id
JOIN (SELECT budget_item_id,
Ifnull(Sum(CASE
WHEN balance_id = 12841 THEN amount
END), 0) AS bal_amount1,
Ifnull(Sum(CASE
WHEN balance_id = 18647 THEN amount
END), 0) AS bal_amount2,
Ifnull(Sum(CASE
WHEN balance_id = 18674 THEN amount
END), 0) AS bal_amount3
FROM balance_lines
GROUP BY budget_item_id) AS bal
ON bal.budget_item_id = bi.id
ORDER BY bi.location
这需要很多时间。在budget_lines和balance_lines表中,每行有超过5,000,000行。
我还附加了查询的EXPLAIN,因此您将能够看到问题。 每个表中的所有ID都被编入索引。是否有任何列,如果将被索引加密查询?或许我需要改变它。
*** LEFT JOIN是必要的,因为我需要从nudget_items中获取所有项目,即使它们在balance / budget_line表中不存在。
架构是:每个预算都有其budget_lines。每个余额都有其balance_lines。该查询旨在使用一个表来总结预算和几个余额之间的差异。
您可以在此处看到更大的图片:http://i.stack.imgur.com/dlF8V.png
修改 在@Sebas回答之后:
对于@sabes饥饿,我在这里写了DESCRIBE: budget_items
budget_lines
balance_lines
答案 0 :(得分:0)
也许是这样的;但没有样本数据和索引很难看到
SELECT *
FROM budget_items bi
WHERE bi.location IS NOT NULL) AS bi
INNER JOIN --Added inner for clarity -changed order I just like my inner's before my outers.
(SELECT budget_item_id, Sum(CASE WHEN balance_id = 12841 THEN coalesce(amount,0) END), 0) AS bal_amount1,
Sum(CASE WHEN balance_id = 18647 THEN coalesce(amount,0) END), 0) AS bal_amount2,
Sum(CASE WHEN balance_id = 18674 THEN coalesce(amount,0) END), 0) AS bal_amount3
FROM balance_lines
WHERE balance_ID in (12841, 18647, 18674) --This way balance_IDs which aren't in this list don't even get evaluated
GROUP BY budget_item_id) AS bal
ON bal.budget_item_id = bi.id
LEFT JOIN
(SELECT budget_item_id, Sum(CASE WHEN budget_id = 21491 THEN coalesce(amount,0) END) AS bud_amount
FROM budget_lines
WHERE budget_Id = 21491 --Again since we only care about anything but budget_ID 21491, we can limit the results to JUST that
GROUP BY budget_item_id) AS bl
ON bl.budget_item_id = bi.id