MySQL查询优化 - 长时间运行的查询

时间:2012-07-26 15:28:24

标签: mysql optimization

我在mysql中有一个查询需要很长时间才能执行。 trans表中有大约350k记录,trans_detail表中有大约1m条记录

我很感激在优化查询或数据库结构方面提供了一些帮助。

查询:

SELECT
    DATE_FORMAT(t.utc_date_due, '%b %Y') AS date_trans,
    LAST_DAY(t.utc_date_due) AS date_end,
    SUM(td.amount * lode) AS 'amount',
    SUM(t.amount_paid * lode) AS 'paid'
FROM trans t
LEFT JOIN trans_detail td ON t.id = td.trans_id AND td.ident = 'c'
WHERE t.company_id = 1
    AND  (trans_type_id = 'inv' or trans_type_id = 'crn')
    AND t.is_deleted = 0
    AND t.is_draft = 0
GROUP BY DATE_FORMAT(t.utc_date_due, '%b %Y')
ORDER BY utc_date_due

explain

+----+-------------+-------+-------------+----------------------------------------------------------+--------------------------------------+---------+----------------+------+-----------------------------------------------------------------------------------------------------+
| id | select_type | table | type        | possible_keys                                            | key                                  | key_len | ref            | rows | Extra                                                                                               |
+----+-------------+-------+-------------+----------------------------------------------------------+--------------------------------------+---------+----------------+------+-----------------------------------------------------------------------------------------------------+
|  1 | SIMPLE      | t     | index_merge | fk_trans_company,fk_trans_trans_type,is_deleted,is_draft | fk_trans_company,is_draft,is_deleted | 4,1,2   | NULL           |  995 | Using intersect(fk_trans_company,is_draft,is_deleted); Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | td    | ref         | fk_trans_detail_trans,ident                              | fk_trans_detail_trans                | 4       | actester2.t.id |    1 |                                                                                                     |
+----+-------------+-------+-------------+----------------------------------------------------------+--------------------------------------+---------+----------------+------+-----------------------------------------------------------------------------------------------------+

2 个答案:

答案 0 :(得分:1)

我首先要更改一行:

AND  (trans_type_id = 'inv' or trans_type_id = 'crn') 

使用IN子句:

AND  (trans_type_id in ('inv', 'crn'))

答案 1 :(得分:0)

尝试放

td.ident = 'c'
WHERE子句中的

。 您可以在utc_date_due上创建索引。

我个人建议,如果速度至关重要,要使用两步法,你应该使用临时表并插入你的元素,然后只在临时表上进行求和。