总共有两个表,一个是"部门"其中包含department_name,department_block_number和department_id(主键),另一个是"学生"其中包含student_name,student_id和department_id(外键)。因此,基于这种情况,我们必须显示具有最大学生数量的部门的名称。
我尝试了一些东西,下面你可以找到我的代码,但它没有按预期工作,所以你能帮我纠正吗?
select u
from
(select count(s.student_id) cnt,d.department_name u
from department d
join student s using(department_id)
group by d.department_name
where cnt==(select max(cntt) from (select
count(ss.student_id) cntt,dd.department_name
from department dd
join student ss using(department_id)
group by dd.department_name)
)
);
注意:此问题属于SubQueries部分。
答案 0 :(得分:0)
您只需要按降序排列所有部门的所有学生,然后限制为第一个结果:
SELECT a.`department_name`
count(b.`student_id`) as `num_students`
FROM `Department` a
JOIN `Student` b
ON a.`department_id` = b.`department_id`
GROUP BY `a.department_id`
ORDER BY count(b.`student_id`) DESC
LIMIT 1;