2013-06-20 42 views
1

我有兩個表:指定別名子查詢的MySQL表

  1. exam表包含學生
  2. 和學生表進行評分

兩者都加入了這個方式:student.id = exam.student_id。

我試圖讓firt五個學生誰在使用下面的查詢超過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,但仍然沒有運氣。

任何想法如何解決這個問題?非常感謝

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

對不起,我犯了我的邏輯錯誤。 如前所述,平均值計算爲

only the last 5 scores recorded

。 更新查詢:

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

你可以發佈你的表定義和一些示例數據嗎? – Kickstart

回答

1

只需將std_id替換爲student.id - 在子查詢編譯過程中,別名尚不存在,因爲直到子查詢被認爲有效(且其輸出已知)才能編譯外部查詢。

+0

謝謝,但我已經嘗試過,但收到錯誤消息#1054 - 'where子句'中的未知列'student.id' – Lomse

+0

[您有另一個問題](http://sqlfiddle.com/#!2/7369b/2)。 –

+0

你們是對的,對不起我犯了我的邏輯錯誤。我剛剛更新了我的問題。謝謝 – Lomse

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 
+0

你們是對的,對不起我犯了我的邏輯錯誤。我剛剛更新了我的問題。謝謝 – Lomse