LeetCode刷题-数据库(MySQL)-1076. Project Employees II

1076. Project Employees II

一、题目描述

Table: Project

Column Name Type
project_id int
employee_id int

(project_id, employee_id) is the primary key of this table.
employee_id is a foreign key to Employee table.

Table: Employee

Column Name Type
employee_id int
name varchar
experience_years int

employee_id is the primary key of this table.

Write an SQL query that reports all the projects that have the most employees.

The query result format is in the following example:

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

The first project has 3 employees while the second one has 2.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/project-employees-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、思路分析

本题要查询所有项目(project)中拥有最多雇员的项目。需注意以下两点:

  1. 要找出每个项目中的雇员数量,需要对 project_id 使用GROUP BY,然后对每个项目的雇员进行加和。因project表的主键是(project_id, employee_id),所以不会存在重复条目。
  2. 另外一点是,如果存在多个项目的雇员数相等且最多,为避免答案不全,就需要先计算出最大雇员数,然后再查询雇员数与最大雇员数相等的项目即可。

三、代码实现

SELECT
	project_id
FROM
	Project
GROUP BY
	 project_id
HAVING 
	COUNT(*) = (
		SELECT
			COUNT(employee_id) cnt
		FROM
			Project
		GROUP BY
			project_id
		ORDER BY
			cnt DESC
		LIMIT 1
	);

你可能感兴趣的:(MySQL)