我想知道在以下示例中使用子查询的解决方案是否是最佳方式:
SELECT
group_id,
student_completed_lectures.student_id,
count(student_completed_lectures.lecture_id) as completed_lectures_count
FROM group
LEFT JOIN group_students ON (group_students.group_id = group.id AND group_students.year = 2011)
LEFT JOIN student_completed_lectures ON (
student_completed_lectures.student_id = group_students.student_id AND
student_completed_lectures.lecture_id IN (
SELECT lecture_id
FROM lecturesets
WHERE lecturesets.id = group.lectureset_id ) )
GROUP BY student_completed_lectures.student_id
这个想法是计算一个学生从已经分配给他的小组的课程中完成了多少次课程。
答案 0 :(得分:0)
如果你想限制结果,你应该这样做
SELECT
group_id,
student_completed_lectures.student_id,
count(student_completed_lectures.lecture_id) as completed_lectures_count
FROM group
LEFT JOIN group_students ON (group_students.group_id = group.id AND group_students.year = 2011)
LEFT JOIN student_completed_lectures ON (
student_completed_lectures.student_id = group_students.student_id)
WHERE student_completed_lectures.lecture_id IN(
SELECT lecture_id
FROM lecturesets
WHERE lecturesets.id = group.lectureset_id )
GROUP BY student_completed_lectures.student_id