Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I re-use an expression in a MySQL query as a variable for another field?

Tags:

mysql

Is there any workaround so I can actually do something like this without having to repeat the entire expression or force a UNION or temporary table?

SELECT  (complex expression) AS variable1,
        (complex expression based on variable1) AS variable2

Since variable1 is not defined and available to the 2nd item because of how mysql works, the above concept can never work.

I either have to repeat the expression for variable2, or use a UNION or a temporary table and use two passes.

Is there some trick that I am not aware of to accomplish this more efficiently?

(note that I need to know the answer for both variable1 and variable2 as they are then used for an INSERT)

Thanks for any ideas!

like image 334
ck_ Avatar asked Sep 02 '09 14:09

ck_


1 Answers

push the first calculation in to a derived table:

select variable1
     , complex_function(variable1, other_column) as variable2
     , yet_another column
  from (select complex_operation as variable1
             , other_column
             , yet_another_column
          from whatever) dt
like image 196
longneck Avatar answered Sep 28 '22 08:09

longneck