如何优化我的MySQL查询?

时间:2011-08-15 18:41:51

标签: mysql

我在优化MySQL查询时遇到了困难。我必须使用现有的数据库结构,但在某些情况下我的响应速度非常慢。

我的查询是:

SELECT 
    `t`.*,
    `p`.`trp_name`,
    `p`.`trp_lname`,
    `trv`.`trv_prosceslevel`,
    `trv`.`trv_id`,
    `v`.`visa_destcountry`,
    `track`.`track_id`,
    `track`.`track_datetoembassy`,
    `track`.`track_expectedreturn`,
    `track`.`track_status`,
    `track`.`track_comments`
FROM
    (SELECT 
        *
    FROM
        `_transactions`
    WHERE
        DATE(`tr_datecreated`) BETWEEN DATE('2011-07-01 00:00:00') AND DATE('2011-08-01 23:59:59')) `t`
        JOIN
    `_trpeople` `p` ON `t`.`tr_id` = `p`.`trp_trid` AND `p`.`trp_name` = 'Joe' AND `p`.`trp_lname` = 'Bloggs'
        JOIN
    `_trvisas` `trv` ON `t`.`tr_id` = `trv`.`trv_trid`
        JOIN
    `_visas` `v` ON `trv`.`trv_visaid` = `v`.`visa_code`
        JOIN
    `_trtracking` `track` ON `track`.`track_trid` = `t`.`tr_id` AND `p`.`trp_id` = `track`.`track_trpid` AND `trv`.`trv_id` = `track`.`track_trvid` AND `track`.`track_status` IN ('New','Missing_Info',
        'En_Route',
        'Ready_Pickup',
        'Received',
        'Awaiting_Voucher',
        'Sent_Client',
        'Closed')
ORDER BY `tr_id` DESC

上述解释说明的结果是:

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   PRIMARY     <derived2>  ALL     NULL    NULL    NULL    NULL    164     Using temporary; Using filesort

1   PRIMARY     track   ALL     status_index    NULL    NULL    NULL    4677    Using where

1   PRIMARY     p   eq_ref  PRIMARY     PRIMARY     4   db.track.track_trpid    1   Using where

1   PRIMARY     trv     eq_ref  PRIMARY     PRIMARY     4   db.track.track_trvid    1   Using where

1   PRIMARY     v   eq_ref  visa_code   visa_code   4   db.trv.trv_visaid   1   

2   DERIVED     _transactions   ALL     NULL    NULL    NULL    NULL    4276    Using where

查询时间是可接受的,直到最后track.track_status IN子句中包含'Closed'的值。然后,时间长度比其他查询增加大约10到15倍。

这是有道理的,因为“已关闭”状态是指所有已处理交易的客户,相当于数据库的约90%至95%。

问题是,在某些情况下,搜索大约需要45秒,这是荒谬的。我确信MySQL可以做得更好,这只是我的错误查询,即使表有4000行,但我无法弄清楚如何优化这个语句。

对于我出错的地方以及如何实施此查询以产生更快的结果,我将不胜感激。

非常感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT t.*, 
p.trp_name, 
p.trp_lname, 
trv.trv_prosceslevel, 
trv.trv_id,
v.visa_destcountry, 
track.track_id, 
track.track_datetoembassy,
track.track_expectedreturn, 
track.track_status, 
track.track_comments 
FROM 

_transactions t
JOIN _trpeople p ON t.tr_id = p.trp_trid
JOIN _trvisas trv ON t.tr_id = trv.trv_trid 
JOIN _visas v ON trv.trv_visaid = v.visa_code 
JOIN _trtracking track ON track.track_trid = t.tr_id 
AND p.trp_id = track.track_trpid 
AND trv.trv_id = track.track_trvid 
WHERE DATE(t.tr_datecreated) 
    BETWEEN DATE('2011-07-01 00:00:00') AND DATE('2011-08-01 23:59:59')

    AND track.track_status IN ('New','Missing_Info','En_Route','Ready_Pickup','Received','Awaiting_Voucher','Sent_Client', 'Closed') 
    AND p.trp_name = 'Joe' AND p.trp_lname = 'Bloggs' 
ORDER BY tr_id DESC