views:

170

answers:

3

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!

A: 
SELECT @v1:=(complex expression) AS variable1,
       (complex expression * @v1) AS variable2
longneck
I am going to be horrified if it's simply that easy and I honestly couldn't figure it out, but thank you!
_ck_
Ah, you know what? The manual page listed above by knittl has repeated warnings not to use or rely on variables set in the same SELECT statement as the fields may be executed out of order based on the WHERE, etc. and the variable is held from the previous execution.So re-using variables within the same SELECT is probably a bad idea, it's meant for sequential queries.
_ck_
i've personally never seen the behavior warned about in the manual, even after trying to make it happen. but if the manual warns against it, then i wouldn't use it. *bleh*
longneck
A: 

i think the only way is to repeat your first complex_expression in your second one, although i thought mysql could handle such cases.

edit: a quick search turned up this: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html

knittl
Thank you for the link, somehow I completely missed that part of MySQL!
_ck_
Your link to the manual was very helpful in understanding why longneck's solution was flawed, thanks again.
_ck_
+1  A: 

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
longneck
It's messier than I wanted but I am going to give you best answer for all your effort, thank you.
_ck_