2

I am trying to limit my count results to those that meet a specific criteria. I am currently using a WHERE clause and my output is as expected.

Here is my current query, and as you can see *ads_list* and *ads_cate* records will only be fetched if my WHERE recdate meets the 14 day mark:

$queryCats = "
SELECT ads_cate.cateName, COUNT(ads_list.Title)
FROM
ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category 
WHERE to_days(now())<=(to_days(recdate)+14)
GROUP BY ads_cate.cateName";

I would like all categories and ads retrieved, but counted ONLY when they meet my WHERE clause criteria. I have been using the HAVING with 0 luck like below. Maybe there is a better way?

$queryCats = "
SELECT ads_cate.cateName, ads_list.recdate, COUNT(ads_list.Title)
FROM
ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category 
GROUP BY ads_cate.cateName
HAVING to_days(now())<=(to_days(recdate)+14)";
3
  • your first query already does that Commented Jun 23, 2011 at 20:04
  • Which table does recdate belong to? Commented Jun 23, 2011 at 20:05
  • The problem is my categories are not in my array to display in my results set. they are being filtered. I need all category names available in my array regardless of they meet that criteria or not. Commented Jun 23, 2011 at 20:06

3 Answers 3

3

Try using a LEFT JOIN and make the date test part of the join condition:

SELECT ac.cateName, COUNT(al.Title)
    FROM ads_cate ac
        LEFT JOIN ads_list al
            ON ac.id = al.category 
                AND to_days(now())<=(to_days(al.recdate)+14)
    GROUP BY ac.cateName
Sign up to request clarification or add additional context in comments.

3 Comments

Joe, your sample was magic. I am guessing the al. Your presentation and approach is new to me such as the al. abbreviation on the LEFT JOIN.. I am guessing the al.Title (al portion) assigns the table that alias. Thanks for the interesting code.
You guessed right. The al alias is just a short hand way of referencing the ads_list table throughout the query. The alias is actually assigned when the table is referenced during the LEFT JOIN ads_list al portion of the code.
I see what you mean in that "ads_list al" fragment. Thanks for the helpful lesson.
1

This may work:

SELECT ads_cate.cateName, ads_list.recdate, COUNT(CASE WHEN to_days(now())<=to_days((recdate)+14) THEN ads_list.Title ELSE NULL END) AS Title
FROM
ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category 
GROUP BY ads_cate.cateName

1 Comment

Try with ELSE NULL, not ELSE 0 because COUNT() counts everything that is not NULL.
0

Put your filtered counting in a subquery and then LEFT JOIN from the category table to the subquery.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.