是否可以在哪里使用别名?

时间:2017-07-21 16:44:43

标签: mysql select join where alias

是否可以使用from avg(n.nota) as media子句中的别名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 
WHERE media > 6 GROUP BY nome;

错误:ERROR 1054 (42S22): Unknown column 'media' in 'where clause'

我使用联接来合并列,我不想使用子选择,如 this question

中所述

有可能吗?

1 个答案:

答案 0 :(得分: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;