MySQL:如何用两个相同的子查询优化查询?

时间:2012-07-26 15:31:58

标签: mysql

我的查询工作正常,但它有2个相同的子查询

SELECT *, 
    (SELECT count(O.id) FROM `offer` O WHERE O.product_id = P.id) AS poffers 
FROM `product` P 
JOIN product_section PS ON (PS.product_id = P.id AND PS.section_id IN (14)) 
WHERE P.deleted is NULL 
    AND (SELECT count(O.id) FROM `offer` O WHERE O.product_id = P.id) > 0 

我尝试使用JOIN进行优化,但新查询返回空结果

SELECT *, OJ.pcount AS poffers
FROM `product` P 
JOIN product_section PS ON PS.product_id = P.id AND PS.section_id IN (14)
JOIN (SELECT count(O.id) AS pcount, O.product_id FROM `offer` O ) 
    AS OJ ON OJ.product_id = P.id
WHERE P.deleted is NULL AND OJ.pcount > 0 

比我尝试变量,但我认为我使用它错了,查询返回空结果

SELECT *,  
    @o := (SELECT count(O.id) FROM `offer` O WHERE O.product_id = P.id) 
    AS poffers 
FROM `product` P 
JOIN product_section PS ON (PS.product_id = P.id AND PS.section_id IN (14)) 
WHERE P.deleted is NULL 
    AND @o > 0 

2 个答案:

答案 0 :(得分:1)

试一试(未经测试)

SELECT P.*,PS.*,count(O.id) AS oCount
FROM `product` P
INNER JOIN `product_section` PS ON (PS.product_id = P.id)
INNER JOIN `offer` O ON (O.product_id = P.id) 
WHERE P.deleted is NULL AND PS.section_id =14
GROUP BY O.product_id
HAVING oCount> 0 

更优化

SELECT P.*,PS.*,count(O.id) AS oCount
FROM `product` P
INNER JOIN (`product_section` PS,`offer` O) ON 
(PS.product_id = P.id AND O.product_id = P.id) 
WHERE P.deleted is NULL AND PS.section_id =14
GROUP BY O.product_id
HAVING oCount> 0 

提示:

  • 不要使用*,而是只编写要检索的列名
  • 为使用ON&的所有列创建索引WHERE条件

Reference

答案 1 :(得分:1)

避免使用从属子查询。相反,有一个查询涉及产品提供计数。您可以在多个地方使用此查询。它很可能暂时存储在内存中,避免重复计算,但数据库引擎也可以做更多聪明的事情。

SELECT *, O.cnt AS poffers
FROM product P
JOIN product_section PS ON (PS.product_id = P.id AND PS.section_id IN (14))
JOIN (SELECT product_id, count(id) AS cnt
      FROM offer
      GROUP BY product_id
     ) O ON (O.product_id = P.id)
WHERE P.deleted is NULL AND O.cnt > 0

如果P和PS之间的关系是一对一的,那么你甚至可以在没有任何副制品的情况下工作:

SELECT *, COUNT(O.id) AS poffers
FROM product P
JOIN product_section PS ON (PS.product_id = P.id AND PS.section_id IN (14))
JOIN offer O ON (O.product_id = P.id)
WHERE P.deleted is NULL
GROUP BY P.id

您还应该考虑是否有充分的理由来计算特定列。在大多数情况下,COUNT(*)会比COUNT(col)更快。使用后者的唯一原因是,如果您明确要从计数中排除NULL值。