我有两张桌子:
exam
表,其中包含学生执行的分数两者都以这种方式加入: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
的地方感谢。
答案 0 :(得分:1)
只需用std_id
替换student.id
- 在子查询编译期间别名尚不存在,因为在子查询被认为有效(并且其输出已知)之前无法编译外部查询。
答案 1 :(得分:1)
你的代码看起来应该对我有用(至少一旦Niels Keurentjes提出的mod已经完成)。
您可以使用生成的序列而不是相关的子选择。像thi: -
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