Forum Moderators: open
I want to list all blog entires which has comments related to it and display the number of comments for each blog entry. I also want the entry with the last activity at the top.
Here's the SQL query I got atm: (this is simplified and only return the id of the blog entry (parent_id).)
SELECT parent_id, date, COUNT(*) FROM blog_comments GROUP BY parent_id ORDER BY date DESC;
With this, I do get a list of the blog entries and the number of comments. However it's not ordered by the last activity. Whenever I make a comment on one of the blog entries the list doesn't change.
It seems to me that the ORDER BY is applied after the items has been grouped, which means that the date I get for each group isn't the date for the last comment.
Can anyone enlighten me?
Your problem is that you are not grouping by date. To get last activity you need to use MAX(date) - this would make that field aggregate and it should work.
SELECT parent_id, MAX(date), COUNT(*) FROM blog_comments GROUP BY parent_id ORDER BY date DESC;
What did work was doing a subquery where I order the list first. But I'm not sure this is the best way to do it.
SELECT parent_id, date, COUNT(*) FROM (SELECT * FROM blog_comments ORDER BY date DESC) AS t1 GROUP BY parent_id ORDER BY date DESC;