学生们参加各科测试的次数
分析 + 实现
第一步:让学生表和科目表进行笛卡尔积
students 表
subjects 表
-- 学生表和科目表进行笛卡尔积
select
*
from students s
cross join subjects sub;
第二步:使用考试表进行统计,查询每个学生每科测试次数
select
student_id,
subject_name,
count(*) attended_exams
from examinations
group by student_id, subject_name;
第三步:将第一步的结果和第二步结果进行左连接
select
*
from students s
cross join subjects sub
left join (
select
student_id,
subject_name,
count(*) attended_exams
from examinations
group by student_id, subject_name
) grouped
-- 注意这里有两个条件
on s.student_id = grouped.student_id and sub.subject_name = grouped.subject_name;
第四步:查出想要的数据并进行排序
select
s.student_id, s.student_name, sub.subject_name, ifnull(grouped.attended_exams, 0) attended_exams
from students s
cross join subjects sub
left join (
select
student_id,
subject_name,
count(*) attended_exams
from examinations
group by student_id, subject_name
) grouped
on s.student_id = grouped.student_id and sub.subject_name = grouped.subject_name
order by student_id, subject_name;
总结
此题用到了我们很少使用的笛卡尔积,同时分组聚合再次用到
标签:sub,1280,grouped,subject,次数,student,各科,id,name From: https://blog.csdn.net/qq_54889094/article/details/143168362