2015-01-17 127 views
0

對於用於我的廣告的每個類別,我想顯示廣告的總數。MySQL:查詢中的WHERE子句與COUNT和GROUP BY?

我當前的查詢看起來是這樣的:

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 

我與包括其specificies,只有那些廣告中顯示,其持續時間仍是有效的WHERE子句中掙扎。我想有間「FROM廣告」和下列條款「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

你的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 
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