1

我有两张桌子:

  1. exam包含学生成绩的表格
  2. 和学生表

两者都以这种方式加入:student.id=exam.student_id。

我正在尝试使用以下查询获得前五名得分最高的学生,这些学生通过 5 天内的平均得分计算得出:

SELECT 
    student.id as std_id, 
    student.name, 
    (SELECT AVG(score) FROM exam WHERE exam.student_id=std_id ORDER BY exam.timestamp DESC LIMIT 5) AS score 

FROM student 
ORDER BY score 
DESC LIMIT 5

我有以下错误:

#1054 - Unknown column 'std_id' in 'where clause'

我也尝试用student.id替换std_id,但仍然没有运气。

知道如何解决这个问题吗?十分感谢

------------------------------------------------------------------------------

对不起,我在逻辑上犯了一个错误。如前所述,平均值计算为

仅记录最后 5 个分数

. 更新查询:

SELECT 
    student.id as std_id, 
    student.name, 
    (SELECT AVG(score) FROM (SELECT score FROM exam WHERE exam.student_id=student.id ORDER BY exam.timestamp DESC LIMIT 5) AS score) AS score 
FROM student 
ORDER BY score 
DESC LIMIT 5

给出错误的地方是我设置exam.student_id=student.id

谢谢。

4

2 回答 2

1

只需替换std_idstudent.id- 在子查询编译期间别名尚不存在,因为在子查询被认为有效(并且其输出已知)之前无法编译外部查询。

于 2013-06-20T12:02:56.507 回答
1

您的代码看起来应该对我有用(至少在 Niels Keurentjes 建议的 mod 完成后)。

您可以使用生成的序列而不是相关的子选择。像这样的东西: -

SELECT 
    student.id, 
    student.name, 
    AVG(Sub3.score)
FROM student
LEFT OUTER JOIN (
    SELECT Sub1.student_id, Sub1.score, @aSeq := IF(@PrevStudent = student_id, @aSeq + 1, 0) AS Sequence, @PrevStudent := student_id
    FROM (SELECT * FROM exam ORDER BY student_id, timestamp DESC) Sub1
    CROSS JOIN (SELECT @PrevStudent := 0, @aSeq := 0) Sub2
) Sub3
ON student.id = Sub3.student_id
WHERE (Sub3.Sequence IS NULL OR Sub3.Sequence < 5)
GROUP BY student.id, student.name
于 2013-06-20T12:40:05.840 回答