views:

89

answers:

2

Hi I'd like to do something like the following:

SELECT * FROM tbl_article
JOIN tbl_comments ON tbl_article.id = tbl_comments.article_id
ORDER BY COUNT(tbl_comments.article_id)

Can anyone suggest how I might get this to work?

+2  A: 

This should do the job:

SELECT 
    tbl_article.*, COUNT(tbl_comments.article_id) as total_comments
FROM 
    tbl_article
LEFT JOIN 
    tbl_comments ON tbl_comments.article_id = tbl_article.id
GROUP BY 
    tbl_article.id
ORDER BY 
    COUNT(tbl_comments.article_id)
Daniel Vassallo
Thanks Daniel, same with this - works fine although if there are 0 comments on a particular article then it is not brought back in the results.
Stu
@Stu: Modified my answer to user a left join. Articles with no comments should show in the results, with a count of 0.
Daniel Vassallo
Great got this working now! The only issue was that "GROUP BY tbl_comments.article_id", should be "GROUP BY tbl_article.id".
Stu
@Stu: Great news. Fixed the query in my answer with the correct GROUP BY clause.
Daniel Vassallo
+1  A: 
SELECT * FROM
(
  SELECT tbl_article.id, COUNT(tbl_comments.id) AS CommentCount FROM tbl_article
  LEFT OUTER JOIN tbl_comments ON tbl_article.id = tbl_comments.article_id
  GROUP BY tbl_article.id
) ra
ORDER BY CommentCount DESC

EDIT : I have changed the join type. Articles should appear regardless of whether they have corresponding entries in the comments table. We're also now grouping on the id field in the articles table.

Paul Alan Taylor
Hi Paul, this works great although if there are zero comments, then the article does not show.
Stu
Have a try with this. Soz, bit rushed earlier on :(
Paul Alan Taylor