MySQL:查询中的WHERE子句与COUNT和GROUP BY?

时间:2015-01-17 11:00:49

标签: mysql sql

对于我的广告使用的每个类别,我想显示广告总数。

我当前的查询如下所示:

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

查询有什么问题?

2 个答案:

答案 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