简体   繁体   中英

Optimization query (MySQL)

I have this tables in MYSQL:

products(prodId, Hide)
cat_binds(prodId,SptPath)
params(paramId,prodId,langId,value)

Query

SELECT 
        DISTINCT(params.value) 
FROM 
        products,
        cat_binds, 
        params 
WHERE 
        products.prodId = params.prodId 
        AND 
        params.paramId =  '1' 
        AND 
        params.langId =  '1' 
        AND 
        products.prodId = cat_binds.prodId 
        AND 
        cat_binds.SptPath LIKE '-2147483644\_%' 
        AND 
        products.Hide = '0'

How optimizing this query? How create right indexes which generate less rows wanted for result.

Thanks for help

Use joins instead of cartisians which fetch undesired rows.

SELECT DISTINCT
  (params.value)
FROM products
  LEFT JOIN cat_binds
    ON cat_binds.prodId = products.prodId
  LEFT JOIN params
    ON params.prodId = products.prodId
WHERE params.paramId = '1'
    AND params.langId = '1'
    AND cat_binds.SptPath LIKE '-2147483644\_%'
    AND products.Hide = '0'

Your SQL looks good and if you have added the Primary Index on all the IDs fields i think it will fine . MySQL will also optimized internally to make the order correct . I have only concern about the WHERE condition containing LIKE expression. As you are using the '%' condition in the last I think adding Index to this column will be helpful but if you put '%' in front then index will have not much effect

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