0

我在 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 |                                                                                                     |
+----+-------------+-------+-------------+----------------------------------------------------------+--------------------------------------+---------+----------------+------+-----------------------------------------------------------------------------------------------------+
4

2 回答 2

1

我将从更改行开始:

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

使用 IN 子句:

AND  (trans_type_id in ('inv', 'crn'))
于 2012-07-26T15:30:39.533 回答
0

试着放

td.ident = 'c'

在您的 WHERE 子句中。您可以在 utc_date_due 上创建索引。

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

于 2013-05-18T15:55:23.620 回答