简体   繁体   中英

How to optimize mysql query for performance

I have five tables with join . This query takes more than 5 sec to execute. I have four queries like the one below, so my PHP page takes more than 30 sec to load. I need to improve the performance. Could you please help me? I have struggled for a week. I added indexing.

MY QUERY

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

MY Query EXPLANATION 在此处输入图片说明

Few modification can be done, to improve you query performance. 1. Add index for ValueDisplayOrder, this will improve the sorting performance. 2. Avoid in query per functioning. Remove the "p.pkBrand+0", this add the execution process time. If possible remove the if clause from order by and do the ordering in your PHP code. 3. Move the "p.cgSlug = 'bathroom-fixtures'" code to on clause of product table join to narrow down the inner join result.

Your modified query will look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM