如何优化mysql查询的性能

时间:2014-09-03 09:15:51

标签: php mysql

我有五张表join。此查询执行时间超过5秒。我有四个查询,如下所示,所以我的PHP页面加载时间超过30秒。我需要提高性能。请你帮助我好吗?我已经挣扎了一个星期。我添加了索引。

我的查询

SELECT f.SortField , f.id 
FROM tbl_store_brands AS sb 
INNER JOIN tbl_products AS p
    ON sb.categoryID = p.pkCategory AND sb.brandID = p.pkBrand 
INNER JOIN ModelPrice AS mp ON (p.id = mp.product_id) 
INNER JOIN Brand_Data AS bd ON bd.pkID = p.pkBrand+0 
INNER JOIN tbl_filters AS f
    ON (
        p.pkID = f.pkID and
        p.pkCategory = f.Category AND
        p.cgSlug = 'bathroom-fixtures'
    ) 
WHERE mp.Available = 1
GROUP BY f.SortField
ORDER BY if (
    f.SortField = 'CAPACITY' OR
    f.SortField = 'WIDTH' OR
    f.SortField = 'HEIGHT' OR
    f.SortField = 'DEPTH', 4, f.ValueDisplayOrder
) ASC

我的查询说明 enter image description here

1 个答案:

答案 0 :(得分:0)

可以进行少量修改,以提高查询性能。 1.为ValueDisplayOrder添加索引,这将提高排序性能。 2.避免查询每个功能。删除“p.pkBrand + 0”,这样就添加了执行进程时间。如果可能,从order by中删除if子句并在PHP代码中进行排序。 3.将“p.cgSlug ='bathroom-fixtures'”代码移动到product table join的on子句,以缩小内部联接结果。

您修改后的查询将如下所示:

SELECT f.SortField , f.id 
FROM tbl_store_brands AS sb 
INNER JOIN tbl_products AS p
    ON sb.categoryID = p.pkCategory AND sb.brandID = p.pkBrand AND  p.cgSlug = 'bathroom-fixtures'
INNER JOIN ModelPrice AS mp ON (p.id = mp.product_id) 
INNER JOIN Brand_Data AS bd ON bd.pkID = p.pkBrand
INNER JOIN tbl_filters AS f
    ON (
        p.pkID = f.pkID and
        p.pkCategory = f.Category

    ) 
WHERE mp.Available = 1
GROUP BY f.SortField
ORDER BY f.ValueDisplayOrder
 ASC