2015-09-20 53 views
0

下面的查詢成功返回誰已打印的最具體的用戶(通過ID)後:無效使用GROUP BY的運營商WHERE子句

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints` 
INNER JOIN `user` on file_prints.user_id = user.user_id GROUP BY 
file_prints.user_id 
ORDER BY sum(print_pages) 

當我介紹where子句來儘量消除用戶誰在所有未打印(也就是,其中sum(print_pages)== 0),我寫了下面的查詢:

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints` 
INNER JOIN `user` on file_prints.user_id = user.user_id WHERE 
sum(print_pages) > 0 GROUP BY file_prints.user_id 
ORDER BY sum(print_pages) 

,並出現以下錯誤:

#1111 - Invalid use of group function 

如何消除sum(print_pages)有0的結果?

回答

1

這是因爲你不能使用聚合函數WHERE條款。因此,使用HAVING這樣的子句:

SELECT file_prints.user_id, user.major, sum(print_pages) 
FROM `file_prints` 
INNER JOIN `user` on file_prints.user_id = user.user_id 
GROUP BY file_prints.user_id 
HAVING sum(print_pages) > 0 
ORDER BY sum(print_pages) 
0

您需要使用具有關鍵字,而不是因爲你是工作的一個總:

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints` 
INNER JOIN `user` on file_prints.user_id = user.user_id 
GROUP BY file_prints.user_id 
HAVING sum(print_pages) > 0 
ORDER BY sum(print_pages)