0

有什么想法可以优化以下 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

谢谢!

4

1 回答 1

0

Remove the in(select ...) and roll it into the main query as more joins. Here's my guess, since I don't know your table structures:

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 
于 2012-11-21T23:18:10.100 回答