题目描述

(通过次数17,269 | 提交次数35,027,通过率49.30%)

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名员工。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/project-employees-ii
//测试数据
Create table If Not Exists Project (project_id int, employee_id int);
Create table If Not Exists Employee (employee_id int, name varchar(10), experience_years int);

insert into Project (project_id, employee_id) values ('1', '1');
insert into Project (project_id, employee_id) values ('1', '2');
insert into Project (project_id, employee_id) values ('1', '3');
insert into Project (project_id, employee_id) values ('2', '1');
insert into Project (project_id, employee_id) values ('2', '4');

insert into Employee (employee_id, name, experience_years) values ('1', 'Khaled', '3');
insert into Employee (employee_id, name, experience_years) values ('2', 'Ali', '2');
insert into Employee (employee_id, name, experience_years) values ('3', 'John', '1');
insert into Employee (employee_id, name, experience_years) values ('4', 'Doe', '2');

解题思路

Project表保存了项目下所有成员的信息。

题目要求:查询项目成员最多的项目。如果有多个项目的项目成员并列第一,需要列出所有项目。

虽然题目提供了两张表,但查询要求中的项目ID、员工ID在Project表中都有,所以,只需要查询Project表即可。

根据Project表,可以先计算出每个项目下的成员数。如果某个项目下的成员数最多,那么,它的成员数一定大于等于所有项目的成员数。使用ALL关键字,可以与集合中的所有行进行比较。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select
    a.project_Id
from Project a
group by a.project_Id
having count(1) >= all (
    select count(1) 
    from Project
    group by project_Id
);
picture loss