Search code examples
mysqlparameter-passingaliases

can you pass a mysql column alias to a user defined function


I have a select statement which displays a number of counts based on different criteria

I want to pass the counts to a user defined function (UDF) to do some calculations

e.g.

SELECT 
player, 
COUNT(IF(action=1,1,NULL)) AS tot_bullseye, 
COUNT(IF(action=2,1,NULL)) AS tot_twentys

UDF(tot_bullseye, tot_twentys)

Solution

  • No, column aliases can never be accessed in the SELECT or WHERE clause for the same query. You have to either repeat the expression, or use a subquery:

    SELECT player, tot_bullseye, tot_twentys, UDF(tot_bullseye, tot_twentys)
    FROM (SELECT player,
                 COUNT(IF(action=1,1,NULL)) AS tot_bullseye,
                 COUNT(IF(action=2,1,NULL)) AS tot_twentys
          ...) AS subq