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)";
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
将过滤后的计数放入子查询中,然后从类别表中将LEFT JOIN
放入子查询中。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.