对于我的广告使用的每个类别,我想显示广告总数。
我当前的查询如下所示:
SELECT
categories_adverts.category,
COUNT(adverts.id) AS numberOfAdverts
FROM adverts
LEFT JOIN categories_adverts
ON adverts.id_categories_adverts=categories_adverts.id
GROUP BY category ASC
我正在努力包括一个WHERE子句,该子句只显示那些持续时间仍然有效的广告。我试图在“FROM adverts”和“LEFT JOIN ...”之间加入以下条款:
WHERE TIME_TO_SEC(timediff(now(),adverts.stamp_created))<=adverts.duration
所以整个查询都是这样的,但这不起作用:
SELECT
categories_adverts.category,
COUNT(adverts.id) AS numberOfAdverts
FROM adverts
WHERE TIME_TO_SEC(timediff(now(),adverts.stamp_created))<=adverts.duration
LEFT JOIN categories_adverts
ON adverts.id_categories_adverts=categories_adverts.id
GROUP BY category ASC
查询有什么问题?
答案 0 :(得分:0)
where
子句位于join
之后
SELECT c.category,
COUNT(a.id) AS numberOfAdverts
FROM adverts a
LEFT JOIN categories_adverts c ON a.id_categories_adverts = c.id
WHERE TIME_TO_SEC(timediff(now(),a.stamp_created)) <= a.duration
GROUP BY c.category ASC
答案 1 :(得分:0)
您的WHERE子句应该在您加入之后以及分组和排序之前, 像这样:
SELECT
categories_adverts.category,
COUNT(adverts.id) AS numberOfAdverts
FROM adverts
LEFT JOIN categories_adverts
ON adverts.id_categories_adverts=categories_adverts.id
WHERE TIME_TO_SEC(timediff(now(),adverts.stamp_created))<=adverts.duration
GROUP BY category ASC