如何優化以下查詢:如何優化下面使用三級select語句的查詢?
我有兩個表'calendar_table'和'consumption',在這裏我使用這個查詢來計算每年的每月消費。
日曆表具有2005年至2009年的日,月和年,消費表已針對每月帳單週期收取消費數據。該查詢將計算每個賬單的天數,並使用該查找每個月的消耗。
SELECT id,
date_from as bill_start_date,
theYear as Year,
MONTHNAME(STR_TO_DATE(theMonth, '%m')) as month,
sum(DaysOnBill),
TotalDaysInTheMonth,
sum(perDayConsumption * DaysOnBill) as EstimatedConsumption
FROM
(
SELECT
id,
date_from,
theYear,
theMonth, # use theMonth for displaying the month as a number
COUNT(*) AS DaysOnBill,
TotalDaysInTheMonth,
perDayConsumption
FROM
(
SELECT
c.id,
c.date_from as date_from,
ct.dt,
y AS theYear,
month AS theMonth,
DAY(LAST_DAY(ct.dt)) as TotalDaysInTheMonth,
perDayConsumption
FROM
consumption AS c
INNER JOIN
calendar_table AS ct
ON ct.dt >= c.date_from
AND ct.dt<= c.date_to
) AS allDates
GROUP BY
id,
date_from,
theYear,
theMonth) AS estimates
GROUP BY
id,
theYear,
theMonth;
大約需要1000秒才能完成大約100萬條記錄。可以做些什麼來使其更快?
在你的calendar_tables ...「dt」列是一個日期/時間?如果是這樣,是不是所有的「時間」部分都是12:00:00(午夜/開始)? – DRapp 2014-10-27 16:53:42
這只是一個日期 – 2014-10-27 17:02:32