优化MySQL查询 - 长运行时

时间:2012-11-21 20:59:01

标签: mysql

有什么想法来优化以下SQL查询?运行需要很长时间。通常大约3-8秒,具体取决于它是哪种产品。

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

谢谢!

1 个答案:

答案 0 :(得分:0)

删除in(选择...)并将其作为更多连接滚动到主查询中。这是我的猜测,因为我不知道你的桌子结构:

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