I want to give a (select…) column with a certain name that require double quotation marks, but i want to call this column in a WHERE
clause or in a HAVING
clause.
Here’s what i’m trying:
select emp_id ID,
concat(fname, ' ', lname) AS "Nome do funcionário",
(select sum(titles.pub_id = E.pub_id) from titles) AS "Número de livros publicados"
from employee AS E
where "Número de livros publicados" = 7;
I managed to do it using the HAVING
clause, but i had to change "Número de livros publicados"
to Total
, but I did want the other alias.
select emp_id AS ID,
concat(fname, ' ', lname) AS "Nome do funcionário",
(select sum(titles.pub_id = E.pub_id) from titles) AS Total
from employee E
having Total = 7;
Is there a way to do it without changing its alias?
3
Answers
Here’s how I would write the query:
In MySQL, you cannot use aliases directly in the
WHERE
clause because theWHERE
clause is processed before theSELECT
clause where aliases are defined. However, you can use aliases in theHAVING
clause because it is processed after theSELECT
clause.To use the alias
"Número de livros publicados"
without changing it, you can modify your query to use theHAVING
clause like this:This approach allows you to check the condition on the alias
"Número de livros publicados"
using theHAVING
clause instead of theWHERE
clause.Source: MySQL Documentation.
A simple trick would be to make a subquery to select all results and give aliases there, then surround it with outer query, which applies
WHERE
clause, recognizing the quoted text as a column name of the subquery. It will, however, worsen its performance somehow.