I am trying to optimize this slow query. It keeps showing up in my slow query log.
SELECT b.*, bc.blog_id, COUNT(bc.blog_id) AS numcomments FROM blog b
LEFT OUTER JOIN blog_comments bc ON b.id = bc.blog_id GROUP BY date DESC LIMIT 0, 5;
It selects all of the blog posts 0, 5 and counts the number of comments associated with each post. We have about 60,000 comments on our blog, so the query is getting clunky. There is an INDEX on bc.blog_id field in the comments table, btw.
Ahhh – thanks so much. This is exactly it and what I need. Thanks again.
Just for my own personal learning knowledge: you use COALESCE to make sure that, in the event that there are no comments, numcomments evaluates to 0, correct?
the purpose of GROUP BY is to aggregate, to collapse a number of rows down to one result row
you were thinking of ORDER BY
SELECT b.*
, COALESCE(bc.cmts,0) AS numcomments
FROM blog AS b
LEFT OUTER
JOIN ( SELECT blog_id
, COUNT(*) AS cmts
FROM blog_comments
GROUP
BY blog_id ) AS bc
ON bc.blog_id = b.id
ORDER
BY b.`date` DESC LIMIT 0, 5