mysql - using sql variable in sum() like this--sum(@wokao) cause unpredicted result -


query 1)

select * test;  ----------- |no1|no2| ----+------ |1  |   1 | |2  |   2 | |3  |   3 | |4  |   4 | |5  |   5 | ----+------ 

query 2)

select @wokao:= (no1 + no2), @wokao test group no1;  2   2 4   4 6   6 8   8 10  10 

query 3)

select @wokao:= (no1 + no2), sum(@wokao) test group no1;  2   null 4   2 6   4 8   6 10  8 

the result of last sql query confusing. why doesn't output second query result?

i ask question because searched keyword of "sum() sql variable" in google , stackoverflow , got nothing. , got problem when wrote sql query @ work query transaction information using sql variable in sum() , lot of subquery.

i appreciate explain question.

as per mysql documentation

as general rule, other in set statements, should never assign value user variable , read value within same statement.for other statements, such select, might results expect, not guaranteed.

in following statement, might think mysql evaluate @a first , assignment second:

select @a, @a:=@a+1, ...; 

however, order of evaluation expressions involving user variables undefined.

so in second query, @wokao first evaluate calculation @wokao:= (no1 + no2), display result while in third query, first display value of sum(@wokao) calculate, , because @ first, value of @wokao null, that's why first display null, , after add subsequent values it.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -