0

I have a mysql query which stores the result in variable, but when I use the same variable later, It doesnt return the same value. Am I missing something?

SELECT 
    duration,
    @sum_duration := (SUM(duration) OVER (
        PARTITION BY user_id,`Date`
    )) as sum_duration,
    @sum_duration
    -- 9*3600*1000*(duration/@sum_duration) as normalized_duration
FROM duration_table

The result of the above query is

'duration', 'sum_duration', '@sum_duration'
'86400000', '172800000',    '783413.000000000000000000000000000000'
'86400000', '172800000',    '783413.000000000000000000000000000000'
'86400000', '172800000',    '783413.000000000000000000000000000000'
'86400000', '172800000',    '172800000.000000000000000000000000000000'
'86400000', '172800000',    '172800000.000000000000000000000000000000'
'86400000', '172800000',    '172800000.000000000000000000000000000000'
'86400000', '172800000',    '172800000.000000000000000000000000000000'
'86400000', '172800000',    '172800000.000000000000000000000000000000'
'86400000', '172800000',    '172800000.000000000000000000000000000000'
'86400000', '172800000',    '172800000.000000000000000000000000000000'

1 Answer 1

0

The problem is (probably) in the definition of "later". The query execution is free to evaluate pieces of the query in whatever order it desires. This makes it difficult to predict whether it is trying to "use" the @ variable before or after it was "set".

And for that reason, @ variables are (or soon will be) deprecated.

If you can provide a small test case with input and desired output, perhaps we can help you rewrite the query to avoid @ variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.