我有这个查询:
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 行。
我还附上了查询的解释,所以你将能够看到问题。每个表中的所有 id 都被索引。是否有任何列会被索引加速查询?或者也许我需要改变它。
*** LEFT JOIN 是必要的,因为我需要从 nudget_items 中获取所有项目,即使它们不存在于 balance/budget_line 表中。
架构是:每个预算都有它的budget_lines。每个余额都有它的 balance_lines。该查询的目的是让一个表来总结预算和几个余额之间的差异。
你可以在这里看到更大的图像:http: //i.stack.imgur.com/dlF8V.png
编辑:
@Sebas 回答后:
对于@sabes 的饥饿感,我在这里放了 DESCRIBE:budget_items
预算线
平衡线