2014-03-28 71 views
0

在此查詢有一個錯誤:SELECT查詢()

"Column 'upload_news.upload_time' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause." 

我想顯示的被兩個日期之間的關係不同的國家與國家名稱的記錄數;

select count(Distinct news_id) AS TotalRecords, country 
from upload_news 
group by country 
having [upload_time] between GetDate()-2 AND GetDate() 
+4

爲什麼不能在where子句中? – xQbert

+0

應該來自聚合函數而不是獨立或孤立的列。 –

+2

錯誤消息完美地解釋了它。您誤解了「HAVING」關鍵字的用途。 –

回答

1

HAVING子句將運行所有的數據進行分組之後,因此只能對分組聚合過濾數據。

如果您想篩選出列中的數據進行分組之前,您需要使用WHERE條款:

select count(Distinct news_id) AS TotalRecords, country 
from upload_news 
where [upload_time] between GetDate()-2 AND GetDate() 
group by country 

注意,WHERE條款需要去GROUP BY條款。

0

這個查詢:

select count(Distinct news_id) AS TotalRecords, country 
from upload_news 
group by country 
having [upload_time] between GetDate()-2 AND GetDate() 

應該是:

select count(Distinct news_id) AS TotalRecords, country 
from upload_news 
where upload_time between (NOW()- INTERVAL 2 DAY) AND NOW() 
group by country 
+0

現在的錯誤是:'NOW'不是公認的內置函數名稱。 @Robert Rozas –

+0

然後你不使用'MySQL'。 –