除聚合函数外,如何优化包含两个相同子查询的查询?

时间:2014-06-28 21:17:26

标签: mysql sql

我试图编写一个直截了当的查询,生成按两件事排名的书籍列表:最近的评论和评论总数。为了计算每本书的最近审查日期,我使用子查询和MIN聚合函数。要计算每本书的评论总数,我使用完全相同的子查询,但使用COUNT聚合函数。

这似乎效率低下。有没有办法将这些子查询合并到一个调用中,并且仍然可以访问查询的HAVING和ORDER BY子句中的两个聚合值?

这是伪问题:

SELECT DISTINCT
    (SELECT MIN(review.pub_date)
        FROM review
        WHERE book.id = review.book_id
        AND ...
        AND ...
        AND ...
    ) AS most_recent_date,
    (SELECT COUNT(review.pub_date)
        FROM review
        WHERE book.id = review.book_id
        AND ...
        AND ...
        AND ...
    ) AS review_count,
    book.id, book.pub_date, book.title, book.author
FROM book
INNER JOIN review
    ON (review.book_id = book.id)
WHERE (
    ...
)
HAVING (most_recent_date > '$DATE')
ORDER BY review_count DESC

我尝试将它们合并为一个并将聚合函数从子查询移动到HAVING和ORDER BY子句中,但我无法以这种方式检索任何结果。

提前致谢。

1 个答案:

答案 0 :(得分:4)

我认为您不需要子查询来执行此操作:

select 
    book.id, book.pub_date, book.title, book.author, 
    min(review.pub_date) as most_recent_date, -- are you sure you want "min"? ("max" makes more sense to me) 
    count(review.pub_date) as review_count
from book
    left join review on book.id = review.book_id
where ... -- Define here any conditions, including those inside the subquery
group by book.id
having most_recent_date > ?
order by review_count desc

优化此方法的其他方法是创建包含所需结果的临时表,然后将结果提取到查询中。