Jump to content

please help me in this query ( add condition to count())


nasser bahaj

Recommended Posts

hi all.

 

please i need your help for this mysql query

 

/////

table 1 (posts):

postid > auto-increment
catid > int
posttitle > varchar
posttext > text
active > int // 1=active , 0=inactive

//////

 

//////

table 2 : (categories):

catid > auto-increment
catname > varchar

//////:

 

so i want to list categories by category name and i want to put beside every category the number of posts in it . i used this query :

 

SELECT categories.catname,COUNT(posts.postid) AS numposts FROM categories LEFT JOIN posts ON categories.catid=posts.catid GROUP BY categories.catname

 

 

this query is working well but the problem is i want to count only the active posts (where active = 1 ) i want to add this condition to count , i tried this query .

 

SELECT categories.catname,COUNT(posts.postid) AS numposts FROM categories LEFT JOIN posts ON categories.catid=posts.catid WHERE posts.active=1 GROUP BY categories.catname

 

but the problem at this query it is select only the categories that has active posts while i want to select all categories but count only ative posts

 

thanks for your time ..

Link to comment
Share on other sites

Hi

 

You can put conditions in the ON clause, which might solve your issue.

 

SELECT categories.catname,COUNT(posts.postid) AS numposts 
FROM categories 
LEFT JOIN posts 
ON categories.catid=posts.catid 
AND posts.active=1
GROUP BY categories.catname

 

This should exclude the inactive posts before the JOIN. Checking in the WHERE clause excludes them after the JOIN, hence drops any rows where there are no matching records.

 

All the best

 

Keith

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.