MySQL query w/ COUNT() and HAVING based on date comparison
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 ad开发者_运维技巧s_list ON ads_cate.id = ads_list.category
GROUP BY ads_cate.cateName
HAVING to_days(now())<=(to_days(recdate)+14)";
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
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
Put your filtered counting in a subquery and then LEFT JOIN
from the category table to the subquery.
精彩评论