0

这是一条 SQL 语句:

SELECT DISTINCT  `class`, `student_id` , `student_name`,
( 
    SELECT SUM(  `credits` ) 
    FROM  `stumgr_scores` B
    JOIN  `stumgr_courses` USING (  `course_id` ) 
    WHERE  `year` =2012 AND A.`student_id` = B.`student_id`
) AS  `total_credits`,
( 
    SELECT SUM( `credits` *  `final_score` )
    FROM  `stumgr_scores` C
    JOIN  `stumgr_courses` USING (  `course_id` ) 
    WHERE  `year` =2012 AND A.`student_id` = C.`student_id`
) AS `total_scores`
FROM  `stumgr_scores` A
NATURAL JOIN  `stumgr_students` 
WHERE  `year` =2012 AND  `grade` =2011

您可能会发现这两个使用聚合函数的 select 语句是相似的。所以,我想将它们合并为一个,如下所示:

SELECT DISTINCT  `class`, `student_id` , `student_name`,
( 
    SELECT 
        SUM(  `credits` ) AS  `total_credits`, 
        SUM( `credits` *  `final_score` ) AS  `total_scores`
    FROM  `stumgr_scores` B
    JOIN  `stumgr_courses` USING (  `course_id` ) 
    WHERE  `year` =2012 AND A.`student_id` = B.`student_id`
) AS `something`
FROM  `stumgr_scores` A
NATURAL JOIN  `stumgr_students` 
WHERE  `year` =2012 AND  `grade` =2011

当然,上面的SQL语句不起作用,我也不知道该怎么办。另外,由于数据量大,查询很慢,您有什么建议吗?非常感谢。

4

1 回答 1

2

我不得不稍微猜测您的表结构,但是您应该能够通过使用JOINs 而不是相关子查询来大规模简化此查询:

SELECT  st.student_id,
        st.student_name,
        c.class,
        SUM(sc.credits) AS total_credits,
        SUM(sc.credits * sc.final_score) AS total_scores
FROM    stumgr_students st
        INNER JOIN stumgr_scores sc
            ON sc.student_id = st.student_id
        INNER JOIN stumgr_courses c
            ON c.course_id = st.course_id
GROUP BY st.student_id, st.student_name, c.class;
于 2013-04-25T11:58:08.457 回答