Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse doctrine alias in select clause

I have the following SELECT clause in Doctrine (the query itself is created using query builder):

u.username,
MAX(p.score) as highscore,
SUM(pc.badgeCount) as badgeCount,
(SUM(pc.badgeCount) / :badgeSum) AS probability,
(-LOG(RAND()) * probability) as weight

(p is an alias for the main entity, pc is a joined one)

This gives me an error message from MySQL:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'probability' in 'field list'

How can I reuse the created aliases within the same SELECT clause?

like image 501
mark.sagikazar Avatar asked Jul 08 '16 08:07

mark.sagikazar


People also ask

Can you use alias in select?

Table Alias. Table aliases can be used in SELECT lists and in the FROM clause to show the complete record or selective columns from a table. Table aliases can be used in WHERE, GROUP BY, HAVING, and ORDER BY clauses.

Can we give alias name in WHERE clause?

The WHERE clause can contain non-correlated aliases and correlated aliases.


1 Answers

I would not call it "reuse". Instead, I would call it "use".

You cannot use an alias until the GROUP BY, HAVING, and ORDER BY clauses.

An alternative might be to use an @variable:

u.username,
MAX(p.score) as highscore,
SUM(pc.badgeCount) as badgeCount,
@prob := (SUM(pc.badgeCount) / :badgeSum) AS probability,
(-LOG(RAND()) * @prob) as weight

The "AS" part still provides the column name for displaying and for those later clauses. Meanwhile, @prob provides a value "immediately".

I say "might" because I think that such use of @variables is going away. The order of evaluation of the SELECT elements is probably "undefined" in the standard. The use shown above depends on the elements to be done in lexical order.

like image 124
Rick James Avatar answered Sep 28 '22 02:09

Rick James