如何优化以下查询:如何优化下面使用三级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