Jump to content

[SOLVED] Help With SELECT COUNT Query


jyushinx

Recommended Posts

Hi,

 

I am having an issue with using the SELECT statement with a COUNT. As far as the database goes. There is an articles table and a response table. Any article can have any number of responses.

 

What I am trying to do is pull an article from the articles table. Part of the information I need however, is the total number of responses. I am trying to do this with a COUNT statement in my SELECT. Here is an example query:

 

SELECT articles.ArticleId,articles.Title,articles.SubmittedWhen,COUNT(responses.ResponseId) AS totalResponses FROM articles,responses WHERE (articles.ArticleId=responses.ArticleId) GROUP BY articles.ArticleId ORDER BY SubmittedWhen

 

Now this query works fine when an article has responses, it pulls the article info plus the number of responses. BUT when an article exists that has no responses, the query does not return it since articles.ArticleId does not equal responses.ArticleId. I'd like this to return the article info plus a 0 for the count.

 

Any ideas as to how I can do this?

 

Thanks.

Link to comment
Share on other sites

When you also want something that doesn't exist, that usually calls for a LEFT JOIN.

 

SELECT
articles.ArticleId,
articles.Title,
articles.SubmittedWhen,
COUNT(responses.ResponseId) AS totalResponses
FROM
articles LEFT JOIN responses ON articles.ArticleId=responses.ArticleId GROUP BY articles.ArticleId ORDER BY SubmittedWhen

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.