无法使用Join执行SQL子查询

时间:2016-11-13 00:15:55

标签: mysql sql join subquery

请有人告诉我,我做得不对。这是我想要执行的查询,但是当我运行命令时没有任何反应。我是SQL的新手,所以请原谅我的错误,如果有的话。

 SELECT  t.*,
 COUNT(DISTINCT t.subjects) AS subjectenrollment,
 u.urefnumber,
 u.uresidence
 FROM 
 (
  SELECT r.*,
  @curRank := IF( @prevRank = finalscore, @curRank, @incRank ) AS position,
  @incRank := @incRank + 1,
  @prevRank = finalscore
  FROM studentsreports r, 
  (
   SELECT @curRank := 0, 
   @prevRank = NULL, 
   @incRank := 1
  ) c
  ORDER BY finalscore ASC
 ) t LEFT JOIN studentstbl u ON t.studref = u.urefnumber
 WHERE t.author = :staff
 AND t.studentname = :student
 AND t.academicyr = :year
 AND t.academicterm = :term
 AND t.program = :program
 AND t.classes = :level
 AND t.subjects = :subject;

从代码中可以看出,我试图获取学生记录,并在每个科目中包含一个职位列,以及提供每个科目的学生人数。更重要的是,我想要包括每个学生的住宿状况,这也在不同的表格中。

在某一点上,我甚至想要添加他们累积的原始分数,即每个科目中获得的所有分数的总和,但我不知道如何使这成为可能。一位朋友已经建议在单独的查询中实现这一点,但不幸的是,我可以做得很好。 拜托,我将非常感谢你的帮助。提前谢谢!

1 个答案:

答案 0 :(得分:0)

使用派生表和相关子查询来考虑此调整,而不需要@variables。下面的SQL语句处理以下列出的使用状态的以下需求:

  1. 每个主题的排名/排名列 - 顶级联合相关计数子查询
  2. 提供每个科目的学生人数 - 汇总计数派生表(内部联接条款)
  3. 每个学生的住宿状况 - 按字段分组(来自子句)
  4. 每个科目中所有分数的总和 - 总和派生表(来自条款)
  5. SQL (带有绑定参数)

    SELECT main.student_number, main.subjects, main.student_residence,
           main.accum_raw_scores, 
           (SELECT COUNT(*) 
            FROM (SELECT s.studref, s.subjects, SUM(s.finalscore) AS total_score
                  FROM studentsreports s
                  GROUP BY s.studref, s.subjects) AS sub
            WHERE sub.subjects = main.subjects
            AND sub.total_score >= main.accum_raw_scores) AS subject_rank,
           cnt.subject_student_count
    FROM
      (SELECT r.studref AS student_number, r.subjects, u.uresidence AS student_residence, 
              SUM(r.finalscore) AS accum_raw_scores       
       FROM studentreports r
       LEFT JOIN studentstbl u ON r.studref = u.urefnumber
       WHERE r.author = :staff
       AND r.studentname = :student
       AND r.academicyr = :year
       AND r.academicterm = :term
       AND r.program = :program
       AND r.classes = :level
       AND r.subjects = :subject
       GROUP BY r.studref, r.subjects, u.uresidence) main
    INNER JOIN 
       (SELECT sub.subjects, COUNT(*) AS subject_student_count 
        FROM studentreports sub 
        GROUP BY sub.subjects) cnt
    ON cnt.subjects = main.subjects