优化MySQL GROUP BY查询

时间:2017-03-18 09:33:09

标签: mysql sql optimization group-by

我需要优化此查询:

SELECT 
    cp.id_currency_purchase,
    MIN(cr.buy_rate),
    MAX(cr.buy_rate)
FROM currency_purchase cp
JOIN currency_rate cr ON cr.id_currency = cp.id_currency AND cr.id_currency_source = cp.id_currency_source
WHERE cr.rate_date >= cp.purchase_date
GROUP BY cp.id_currency_purchase

现在需要大约0.5秒,这对我来说太长了(它经常被更新使用,所以查询缓存在我的情况下没有帮助。)

此处的EXPLAIN EXTENDED输出:

+------+-------------+-------+-------+--------------------------------+-------------+---------+-------------------------+-------+----------+-------------+
| id   | select_type | table | type  | possible_keys                  | key         | key_len | ref                     | rows  | filtered | Extra       |
+------+-------------+-------+-------+--------------------------------+-------------+---------+-------------------------+-------+----------+-------------+
|    1 | SIMPLE      | cp    | index | id_currency_source,id_currency | PRIMARY     | 8       | NULL                    |     9 |   100.00 |             |
|    1 | SIMPLE      | cr    | ref   | id_currency,id_currency_source | id_currency | 8       | lokatnik.cp.id_currency | 21433 |   100.00 | Using where |
+------+-------------+-------+-------+--------------------------------+-------------+---------+-------------------------+-------+----------+-------------+

stackoverflow对于一个GROUP BY优化表有一些很好的问题(例如:https://stackoverflow.com/a/11631480/1320081),但我真的不知道如何根据JOIN-ed表优化查询。

如何加快速度?

1 个答案:

答案 0 :(得分:2)

此查询的最佳索引:

SELECT cp.id_currency_purchase, MIN(cr.buy_rate), MAX(cr.buy_rate)
FROM currency_purchase cp JOIN
     currency_rate cr
     ON cr.id_currency = cp.id_currency AND
        cr.id_currency_source = cp.id_currency_source
WHERE cr.rate_date >= cp.purchase_date
GROUP BY cp.id_currency_purchase;

是:currency_rate(id_currency, id_currency_source, rate_date, buy_rate)。您也可以尝试currency_purchase(id_currency, id_currency_source, rate_date)