I was wondering if my solution of using a subquery in the following example is the most optimal way:
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
The idea is to count how many lectures a student has completed from what has been assigned to his group.
If you want to restrict the results you should do it like this