MySQL - 优化选择查询

时间:2014-04-12 11:59:20

标签: mysql sql database indexing

我在stockmain表中有大约4.4K记录,在stockdetail表中有4.4K记录,在item表中有大约1.04K记录。我有以下查询:

SELECT 
    item.model, 
    stockdetail.docs, 
    item.category, 
    stockdetail.item_id, 
    stockdetail.chasis, 
    stockdetail.price, 
    stockdetail.tax, 
    stockdetail.recycle, 
    stockdetail.auction, 
    stockdetail.shaken, 
    stockdetail.transport, 
    stockdetail.fee, 
    stockdetail.netamount, 
    IFNULL(SUM(QTY),0) as QTY, 
    item.DESCRIPTION 
FROM 
    stockmain 
        INNER JOIN stockdetail 
            ON stockmain.STID=stockdetail.STID 
        INNER JOIN item 
            ON stockdetail.ITEM_ID = item.ITEM_ID 
WHERE 
    stockmain.vrdate 
        BETWEEN '{$startDate}' AND '{$endDate}'
AND stockmain.company_id={$company_id} 
GROUP BY 
    item.item_id, chasis HAVING IFNULL(SUM(QTY),0) > 0 ORDER BY item.description, item.model

加载数据需要大约45-48秒的平均数。如何优化此查询以更快地执行?

P.S我尝试将索引添加到stockmainvrdatestockmaincompany_id,但这没有改变任何内容。

以下是上述查询的EXPLAIN

| id | select_type | table       | type   | possible_keys | key      | key_len |      ref                    | rows  | Extra                            |
| 1  |   SIMPLE    | stockdetail | ALL    |               |          |         |                             |  4180 |  Using temporary; Using filesort |
| 1  |   SIMPLE    | item        | eq_ref | PRIMARY       |  PRIMARY | 4       | kashmir.stockdetail.item_id |  1    |                                  |
| 1  |   SIMPLE    | stockmain   | eq_ref | PRIMARY       |  PRIMARY | 4       | kashmir.stockdetail.stid    |  1    |  Using where                     |

0 个答案:

没有答案