2016-01-27 49 views
2

我需要幫助: 此查詢工作得很好MySql的分組和過濾結果:錯誤

select count(distinct(a.mat)),count(distinct(c.mail)) as nb 
from aca as a 
left join c on c.mat=a.mat 
group by a.mat 
order by nb desc; 

但是當我想篩選

select count(distinct(a.mat)),count(distinct(c.mail)) as nb 
from aca as a 
left join c on c.mat=a.mat 
group by a.mat 
order by nb desc 
where nb > 0; 

我得到這個錯誤

錯誤1064(42000):您的SQL語法有錯誤;檢查對應於您的MySQL服務器版本的手冊,以便在第6行'where nb> 0'附近使用正確的語法。

我的查詢有什麼問題?

回答

2

條件的分組功能應放入HAVING子句:

select count(distinct(a.mat)),count(distinct(c.mail)) as nb 
from aca as a 
left join c on c.mat=a.mat 
group by a.mat 
having nb > 0 
order by nb desc; 
4

排序應該永遠是最後

select count(distinct(a.mat)),count(distinct(c.mail)) as nb 
from aca as a 
left join c on c.mat=a.mat 
group by a.mat 
having nb > 0 
order by nb desc 
+0

我得到錯誤1054(42S22):未知列「,其中 'NB'條款'... – user2129506

+0

忘記它的聚合!編輯 –