2012-11-21 199 views
0

優化以下SQL查詢的任何想法?運行需要相當長的時間。通常大約3-8秒,取決於它是哪種產品。優化MySQL查詢 - 運行時間長

SELECT 
`serviceid` 

FROM 
`services` 

INNER JOIN `products` ON `serviceid`=products.`id` 

WHERE 
`orderid` IN 
(
    SELECT `orderid` FROM `orders_items`,`orders` 

    WHERE 
    `orderid`=orders.`id` AND 
    `status` > '2' AND 
    `serviceid`='___SYSTEM_VARIABLE___' 
) 

AND NOT 
`serviceid`='___SYSTEM_VARIABLE___' AND 
products.`state`='1' AND 
products.`stock` > 0 

GROUP BY 
`serviceid` 

ORDER BY 
COUNT(`serviceid`) DESC LIMIT 15 

謝謝!

+2

你可能會需要向我們展示SHOW的'輸出CREATE TABLE'每個上面提到的表,以及' EXPLAIN SELECT'用於該查詢。 – whamma

回答

0

刪除in(select ...)並將其作爲更多連接滾動到主查詢中。這是我的猜測,因爲我不知道你的表結構:

SELECT 
    `serviceid` 
FROM 
    `services` 
    INNER JOIN `products` 
    ON `serviceid` = products.`id` 
    INNER JOIN `orders` 
    ON `products`.`orderid` = `orders`.`id` 
    INNER JOIN `orders_items` 
    ON `orderid` = `orders`.`id` 
WHERE services.`serviceid` = '___SYSTEM_VARIABLE___' 
    AND products.`state` = '1' 
    AND products.`stock` > 0 
    AND `orders`.`status` > '2' 
    AND `orders`.`serviceid` = '___SYSTEM_VARIABLE___' 
GROUP BY `serviceid` 
ORDER BY COUNT(`serviceid`) DESC 
LIMIT 15