Home  >  Article  >  Database  >  mysqlselect中子查询中使用强制索引的优化案例_MySQL

mysqlselect中子查询中使用强制索引的优化案例_MySQL

WBOY
WBOYOriginal
2016-05-30 17:10:081266browse

1,朋友找我帮忙看下比较慢的sql语句

SELECT
    pg.product_goods_id,
    pg.product_id,
    pg.pdt_code,
    pg.pdt_name,
    pg.brand_name,
    pg.reference_price,
    pg.deposit,
    pg.sale_status,
    pg.is_delete,
    pg.create_date,
    pg.create_operator,
    pg.update_date,
    pg.update_operator,
    si.shop_id,
    si.shop_name,
    pg.goods_img_url,
    pg.is_bargain,
    pg.qr_code_url,
    (
        SELECT
            COUNT(*)
        FROM
            product_attention pa
        WHERE
            pa.product_goods_id = pg.product_goods_id
        AND `status` = 0
    ) AS laud,
    pc.category_name,
    pg.is_experience,
    pg.deposit,
    pg.buy_type,
    pg.content,
    pg.assure_flag,
    pg.market_price,
    pg.qty_cnt,
    pg.sales_cnt
FROM
    product_goods pg 
LEFT JOIN shop_info si ON si.shop_id = pg.shop_id
LEFT JOIN product_category pc ON pc.category_id = pg.category_id
WHERE
    si.market_id IN (1, 2, 3, 12, 13) 
 ORDER BY pg.update_date DESC , pg.product_goods_id DESC
LIMIT 0,
 20;

问题1,加上如下的子查询,比较慢

        (
                SELECT
                    COUNT(*)
                FROM
                    product_attention pa
                WHERE 
                    pa.product_goods_id = pg.product_goods_id
                AND `status` = 0
            ) AS laud,

这里加上去就有点慢,有什么优化办法么,询问有啥方法?

原blog地址:http://blog.csdn.net/mchdba/article/details/49667417,未经原作者同意,谢绝转载。

2,我让他提供了explain分析下执行结果

C:\Users\Administrator\Pictures\1105\e1.jpg
这里写图片描述
从中可以看到,pg表中用到了临时表空间也用到了filesort,这个点比较麻烦了。

3,我让他提供下涉及到的几个表的索引情况

、pa.jpg
这里写图片描述
、si.jpg
这里写图片描述
、pg.jpg
这里写图片描述

几个表的数据量都不大,product_goods 6w多条,其他3千多条。不应该这么慢的。

4,去掉order by后比较快的思考

我猜猜可能是order by引起的,我让去掉order by之后,他说比较快,但是这个order by不能轻易去掉,因为这是也许需要。但是order by字段里面有 product_goods_id。

5,解决方案:强制使用主键索引

分析到引起蛮的order by以及子查询里面都有product_goods_id字段,而且这个字段是pg表的主键,这么可以强制使用主键索引而不走shop_id的索引,我让他采用product_goods pg force index(PRI) 强制使用主键索引,我这样想,主要是因为这个语句的子查询用的是主键关联,但是explain的时候用的是shop_id的索引,我就怀疑是走了这个shop_id的索引导致的。如果不走这个shop_id字段的索引,直接走主键id既然兼顾到了join表链接又兼顾到了子查询了。

结果,他测试了后,发现快了许多,问题解决,expain结果如下ok.jpg所示,已经没有using temporary这一项了。
这里写图片描述

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn