加速SQL查询

时间:2012-12-02 09:04:43

标签: mysql sql performance

我在MySQL数据库中存储了温度。该表称为temperatures。例如,它包含列dtimetemperature。第一个是测量温度的时间(柱类型为DATETIME),后者,显然是温度(类型为FLOAT)。

目前我使用以下查询来获取某段时间内的温度。

SELECT dtime, temperature 
FROM temperatures 
WHERE dtime BETWEEN "2012-11-15 00:00:00" AND "2012-11-30 23:59:59" 
ORDER BY dtime DESC

我想在结果中添加当天的平均温度。我尝试了以下内容。

SELECT 
    dtime AS cPVM,
    temperature,
    (
        SELECT AVG(temperature) 
        FROM temperatures 
        WHERE DATE(dtime) = DATE(cPVM)
    ) AS avg
FROM temperatures 
WHERE dtime BETWEEN "2012-11-15 00:00:00" AND "2012-11-30 23:59:59" 
ORDER BY dtime DESC

工作正常,但这确实很慢。在该时间段内获取结果大约需要5秒,而第一个(没有平均值)在0.03秒内完成。

SELECT DATE(dtime), AVG(temperature) 
FROM temperatures 
WHERE DATE(dtime) BETWEEN "2012-11-15" AND "2012-11-30" 
GROUP BY DATE(dtime) 
ORDER BY dtime DESC

然而,这个是在0.04秒内完成的。

如何更有效地获取平均温度?

2 个答案:

答案 0 :(得分:1)

使用连接而不是相关子查询:

SELECT dtime, temperature, avg_temperature
FROM temperatures 
JOIN (
    SELECT DATE(dtime) AS date_dtime, AVG(temperature) AS avg_temperature
    FROM temperatures
    WHERE dtime >= '2012-11-15' AND dtime < '2012-12-01'
    GROUP BY DATE(dtime)
) AS avg_t
ON date_dtime = DATE(dtime)
WHERE dtime dtime >= '2012-11-15' AND dtime < '2012-12-01'
ORDER BY dtime DESC

答案 1 :(得分:0)

由于您的第一个查询已经非常有效,我们将其作为起点。根据它生成的结果集的大小,查询第一个查询的结果仍然非常有效。

您的第三个查询似乎也运行得非常有效,因此如果我提出的查询效果不佳,您可以回过头来查看。我喜欢它的原因是因为您可以将原始查询作为排序参数(减去ORDER BY)并将其插入到此查询中,其中显示了原始查询的日期范围内的平均温度:

SELECT
    DATE(dtime) AS day_of_interest,
    AVG(temperature) AS avg_temperature
FROM
    (
        -- Your first query is here, minus the ORDER BY clause
        SELECT 
            dtime,
            temperature 
        FROM 
            temperatures 
        WHERE 
            dtime BETWEEN "2012-11-15 00:00:00" AND "2012-11-30 23:59:59" 
        -- ORDER BY irrelevant inside subqueries, only slows you down
        -- ORDER BY 
            -- dtime DESC
    ) AS temperatures_of_interest
GROUP BY
    day_of_interest
ORDER BY
    day_of_interest DESC

如果此查询为您“高效地运行”,那么这可能是一个比其他人更容易编码和自动化的解决方案。

希望这有帮助!