1. 确实,本地可构建个类似的语句来复现,不知缘由:
*( V 站排版原因,开头有全角空格。若要复制运行,记得删除)*
```mysql
WITH
nums(num) AS (
VALUES ROW(1), ROW(2), ROW(3)
)
SELECT @
total, @
total := sum(num)
FROM nums, (SELECT @
total := 0) t
GROUP BY num;
```
2. 如果你只是想要『上一行的数据』,你可以使用*(连 SQLite 都支持的)*窗口函数 `LAG`:
```sql
WITH
nums(num) AS (
VALUES ROW(1), ROW(2), ROW(3) -- SQLite 写法:VALUES (1), (2), (3)
)
SELECT num, LAG(num) OVER(ORDER BY num)
FROM nums;
```
3. 另外,[MySQL 官方文档](
https://dev.mysql.com/doc/refman/8.0/en/user-variables.html ) 很不推荐你图片中的用法:
- 除了 `SET` 语句外,不应在同一条语句内赋值和读取一个用户变量*( 5.7 版本文档: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 )*
- 涉及用户变量的表达式的求值顺序未定义*( 8.0 版本文档:The order of evaluation for expressions involving user variables is undefined. For example, there is no guarantee that SELECT @
a, @
a:=@a+1 evaluates @
a first and then performs the assignment )*
- 『在 `SELECT` 中使用 `:=` 为用户变量赋值』已被弃用,未来会移除*( 8.0 版本文档:Previous releases of MySQL made it possible to assign a value to a user variable in statements other than SET. This functionality is supported in MySQL 8.0 for backward compatibility but is subject to removal in a future release of MySQL )*