项目员工II
Table: Project
+-------------+---------+| Column Name | Type |+-------------+---------+| project_id | int || employee_id | int |+-------------+---------+主键为 (project_id, employee_id)。employee_id 是员工表 Employee 表的外键。
Table: Employee
+------------------+---------+| Column Name | Type |+------------------+---------+| employee_id | int || name | varchar || experience_years | int |+------------------+---------+主键是 employee_id。
编写一个SQL查询,报告所有雇员最多的项目。
查询结果格式如下所示:
Project table:+-------------+-------------+| project_id | employee_id |+-------------+-------------+| 1 | 1 || 1 | 2 || 1 | 3 || 2 | 1 || 2 | 4 |+-------------+-------------+Employee table:+-------------+--------+------------------+| employee_id | name | experience_years |+-------------+--------+------------------+| 1 | Khaled | 3 || 2 | Ali | 2 || 3 | John | 1 || 4 | Doe | 2 |+-------------+--------+------------------+Result table:+-------------+| project_id |+-------------+| 1 |+-------------+第一个项目有3名员工,第二个项目有2名员工。
selectproject_idfrom(selectproject_id,count(employee_id) cntfromProjectgroup byproject_id) twheret.cnt = max(cnt)
Invalid use of group function
where后面是不能跟聚合函数的。
聚合函数要使用的话,有一个前提,那就是是必须要有结果集,根据Mysql的执行步骤,当程序执行到where的时候,mysql是没有结果集的,所以聚合函数不能用在where后面。但是聚合函数为什么就可以放在having后面呢,原因是使用having,前面一定要有分组,而分组的时候就已经有结果了,所以就有结果集了,满足聚合函数前面一定要有结果集的要求。
selectproject_idfromProjectgroup byproject_idhavingcount(employee_id) = max (count(employee_id) )
FUNCTION test.max does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual
子查询的解决方案
project_idfromProjectgroup byproject_idhavingcount(employee_id) =(selectcount(employee_id)fromProjectgroup byproject_idorder bycount(employee_id )desc limit 1)
all的解决方案:
selectproject_idfromProjectgroup byproject_idhavingcount(employee_id) >= all(select count(employee_id) from Project group by project_id )
