How to use pseudo names with CONCAT and Mysql?

Asked

Viewed 97 times

1

A question about Mysql asks the result to exit in this answer format.

inserir a descrição da imagem aqui

When finishing my solution through a consultation made on Mysql, find the following problem.

Below is a first example solution of my query that Works

SELECT CONCAT('There are a total of ' , COUNT(name),' ', occupation ) FROM OCCUPATIONS GROUP BY occupation ORDER BY COUNT(name) ASC ;

Below is a second solution example of my query that Doesn’t Work

SELECT CONCAT('There are a total of ' , COUNT(name) AS Numb,' ', occupation ) FROM OCCUPATIONS GROUP BY occupation ORDER BY Numb ASC ;`

The problem at issue is that I would like to rename the COUNT(name) for numb through a 'alias' or a pseudo name, but I’m faced with this mistake.

ERROR 1583 (42000) at line 3: Incorrect parameters in the call to native function 'concat'

It would be possible to circumvent this problem, that is, it is possible to use pseudo names within the function CONCAT?

2 answers

1

It’s not possible, and in this case it doesn’t even make sense. I initially imagined that I would use the die for something else, as it would not be completely unnecessary to name the result of the expression used in concatenation.

It makes no sense not to want repetition because the syntax asks for repetition.

1


According to the standard it is not possible to use aliases in the same SELECT statement in which they are created. A solution is to use a sub-query.

The standard states that the sequence of execution of the instructions is as follows::

1. FROM 
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. ORDER BY
7. TOP

This explains, for example, why it is possible to use an alias in the ORDER BY clause.

  • Whenever I use some aggregation function I usually give names to them, in this case it is not to repeat the "COUNT(name)" in the part of GROUP BY.

  • In this case the solution is to use a sub-query to calculate the total, after which you can use the alias in both SELECT and GROUP BY

Browser other questions tagged

You are not signed in. Login or sign up in order to post.