2017-07-21 23 views
-1

是否可以使用來自WHERE子句的別名from avg(n.nota) as media是否可以在別處使用別名?

SELECT a.nome AS nome, c.nome AS curso, avg(n.nota) AS media from Aluno a 
JOIN Matricula m ON m.aluno_id = a.id 
JOIN Curso c ON m.curso_id = c.id 
JOIN Secao s ON s.curso_id = c.id 
JOIN Exercicio e ON e.secao_id = s.id 
JOIN Resposta r ON r.exercicio_id = e.id and r.aluno_id = a.id 
JOIN Nota n ON n.resposta_id = r.id 
WHERE media > 6 GROUP BY nome; 

錯誤:ERROR 1054 (42S22): Unknown column 'media' in 'where clause'

我使用加盟列組合在一起,我不希望使用子查詢,像this question

提到是否有可能呢?

回答

0

爲了使用上集合函數的濾波器,利用HAVING子句代替WHERE子句:

SELECT a.nome AS nome, c.nome AS curso, avg(n.nota) AS media from Aluno a 
    JOIN Matricula m ON m.aluno_id = a.id 
    JOIN Curso c ON m.curso_id = c.id 
    JOIN Secao s ON s.curso_id = c.id 
    JOIN Exercicio e ON e.secao_id = s.id 
    JOIN Resposta r ON r.exercicio_id = e.id and r.aluno_id = a.id 
    JOIN Nota n ON n.resposta_id = r.id 
GROUP BY nome 
HAVING avg(n.nota) > 6; 
相關問題