tags:

views:

411

answers:

2

Hi,

So let's say I want to select the ID of all my blog posts and then a count of the comments associated with that blog post, how do I use GROUP BY or ORDER BY so that the returned list is in order of number of comments per post?

I have this query which returns the data but not in the order I want? Changing the group by makes no difference:

SELECT p.ID, count(c.comment_ID) 
FROM wp_posts p, wp_comments c 
WHERE p.ID = c.comment_post_ID 
GROUP BY c.comment_post_ID;

Thanks

+2  A: 
SELECT p.ID, count(c.comment_ID) AS [count]
FROM wp_posts p, wp_comments c 
WHERE p.ID = c.comment_post_ID 
GROUP BY c.comment_post_ID;
ORDER BY [count] DESC
Dave Bauman
select p.ID, count(c.comment_ID) AS ccount from wp_posts p, wp_comments c where p.ID = c.comment_post_ID GROUP BY c.comment_ID ORDER BY ccount DESC;^^ just returns all the counts as 1 (they are definitely not all 1)..
Adam Taylor
Oh it worked when I did group by p.ID..
Adam Taylor
+3  A: 

I'm not familiar with pre-SQL92 syntax, so I'll express it in a way that I'm familiar with:

SELECT c.comment_post_ID, COUNT(c.comment_ID)
FROM wp_comments c
GROUP BY c.comment_post_ID
ORDER BY COUNT(c.comment_ID) -- ASC or DESC

What database engine are you using? In SQL Server, at least, there's no need for a join unless you're pulling more data from the posts table. With a join:

SELECT p.ID, COUNT(c.comment_ID)
FROM wp_posts p
JOIN wp_comments c ON c.comment_post_ID = p.ID
GROUP BY p.ID
ORDER BY COUNT(c.comment_ID)
Michael Petrotta
That was really just the easiest example for me to play with to get my head around join + count (it's mysql 5.x)
Adam Taylor
Understood. Expanded my answer with a join.
Michael Petrotta