这个语法出了什么问题?

时间:2016-08-13 11:48:20

标签: mysql sql

select count(*),snum from enrolled group by snum where count(*)=(select count(distinct(cname)) from enrolled;);

我正在使用MYSQL 5.7

2 个答案:

答案 0 :(得分:2)

您不能在where子句中使用聚合函数。你想要一个having子句:

select count(*), snum
from enrolled
group by snum 
having count(*) = (select count(distinct cname ) from enrolled);

此外,在查询结尾处只能出现一个分号。并且,虽然这不是语法错误,但distinct不是函数,因此它不需要括号。

答案 1 :(得分:1)

您不能在where子句中使用聚合术语。相反,您应该使用having子句:

SELECT   COUNT(*), snum
FROM     enrolled
GROUP BY snum
HAVING   COUNT(*) = COUNT(DISTINCT(cname))