像这样在 sum() 中使用 sql 变量 --sum(@wokao) 导致不可预测的结果

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

查询 1)

Select * From test;

-----------
|no1|no2|
----+------
|1  |   1 |
|2  |   2 |
|3  |   3 |
|4  |   4 |
|5  |   5 |
----+------

查询 2)

select @wokao:= (no1 + no2), @wokao from test group by no1;

2   2
4   4
6   6
8   8
10  10

查询 3)

select @wokao:= (no1 + no2), sum(@wokao) from test group by no1;

2   null
4   2
6   4
8   6
10  8

上次 SQL 查询的结果令人困惑。为什么不输出类似第二个查询的结果?

我问这个问题是因为我在 google 和 Whosebug 中搜索了 "sum() sql variable" 的关键字,但一无所获。当我在工作中编写 SQL 查询以使用 SUM() 中的 SQL 变量和大量子查询查询交易信息时,我遇到了这个问题。

非常感谢有人能解释这个问题。

根据 MYSQL 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 other statements, such as SELECT, you might get the results you expect, but this is not guaranteed.

在下面的语句中,您可能会认为 MySQL 会先计算 @a 然后再进行赋值:

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

但是,涉及用户变量的表达式的求值顺序未定义

所以在你的第二个查询中,@wokao首先计算@wokao:= (no1 + no2),然后显示结果而在第三个查询中,首先显示sum(@wokao)的值然后计算,并且因为一开始@wokao的值是null,所以先显示null,然后再给它加上后续的值。