我想知道以下示例中使用子查询的解决方案是否是最佳方法:

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


这个想法是要计算一个学生从分配给他的小组的课程中已经完成了多少课。

最佳答案

如果要限制结果,则应这样操作

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

关于mysql - 什么时候(不)在JOIN语句中使用子查询?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8402643/

10-16 14:37