简体   繁体   中英

SQL Select sum query variable

SELECT
@frst:= (1) 
+   
@scnd:= (2) as 'Total',
@frst as 'Frst',
@scndas 'Scnd'

This query returns 3 - 3 - 2 and not 3 - 1 - 2. What am I doing wrong?

What you are doing wrong is assigning variables in one expression and using the values in another. MySQL does not guarantee the order of evaluation of expressions in a select , so this is not safe.

This is explained in the documentation :

As a general rule, other than in SET statements, you should never assign a value to a user variable and read the value within the same statement. For example, to increment a variable, this is okay:

 SET @a = @a + 1;

For other statements, such as SELECT , you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second:

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

However, the order of evaluation for expressions involving user variables is undefined.

Here's what you are doing :

SELECT
@frst:= (1) // *1
+   
@scnd:= (2) as 'Total',// *2
@frst as 'Frst',// *3
@scnd as 'Scnd'// *4

is like :

*1 & *2 => set @frst to 1, set @scnd to 2,add and assign to @frst return as total which is 3 (1 + 2)
*3 => @frst as 'Frst' // return 3 as Frst
*4 => @scnd as 'Scnd' // return 2 as Scnd

and your query returns total which is equal to 3, Frst which is equal to 3 and Scnd which is equal to 2 Hope you get it right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM