这可以通过JOIN
针对获取聚合COUNT()
perthread_id
和聚合的子选择来改进MAX(date)
。而不是评估每一行的子选择,派生表应该为整个查询只评估一次,并与来自community_threads
.
SELECT
community_threads.id AS thread_id,
community_threads.title AS thread_title,
community_threads.date AS thread_date,
community_threads.author_id AS author_id,
`user`.display_name AS author_name,
`user`.organization AS author_organization,
/* From the joined subqueries */
maxdate.date AS reply_date,
threadcount.num AS total_replies
FROM
community_threads
INNER JOIN `user` ON community_threads.author_id = `user`.id
/* JOIN against subqueries to return MAX(date) (same as order by date DESC limit 1) and COUNT(*) from replies */
/* number of replies per thread_id */
INNER JOIN (
SELECT thread_id, COUNT(*) AS num FROM replies GROUP BY thread_id
) threadcount ON community_threads.id = threadcount.thread_id
/* Most recent date per thread_id */
INNER JOIN (
SELECT thread_id, MAX(date) AS date FROM replies GROUP BY thread_id
) maxdate ON community_threads.id = maxdate.thread_id
WHERE
category_id = '1'
ORDER BY
reply_date DESC
LIMIT 0, 5
LIMIT 0, 5
如果将其放在reply_date
子查询中,您可能会获得更好的性能。这只会拉取子查询中最近的 5 个,并且INNER JOIN
将丢弃所有community_threads
不匹配的内容。
/* I *think* this will work...*/
SELECT
community_threads.id AS thread_id,
community_threads.title AS thread_title,
community_threads.date AS thread_date,
community_threads.author_id AS author_id,
`user`.display_name AS author_name,
`user`.organization AS author_organization,
/* From the joined subqueries */
maxdate.date AS reply_date,
threadcount.num AS total_replies
FROM
community_threads
INNER JOIN `user` ON community_threads.author_id = `user`.id
INNER JOIN (
SELECT thread_id, COUNT(*) AS num FROM replies GROUP BY thread_id
) threadcount ON community_threads.id = threadcount.thread_id
/* LIMIT in this subquery */
INNER JOIN (
SELECT thread_id, MAX(date) AS date FROM replies GROUP BY thread_id ORDER BY date DESC LIMIT 0, 5
) maxdate ON community_threads.id = maxdate.thread_id
WHERE
category_id = '1'
ORDER BY
reply_date DESC