【发布时间】:2020-03-24 12:13:29
【问题描述】:
我正在研究以下 mysql:
select num, @record,
case
when @record = num then @count:=@count+1
when @record <> @record:=num then @count:=1 end as n
from
Logs ,(select @count:=0,@record:=(SELECT num from Logs limit 0,1)) r
Logs 表在哪里:
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
查询的输出如下:
|num | @record | n |
----------------------
| 1 | "1" | 1.0 |
| 1 | "1" | 2.0 |
| 1 | "1" | 3.0 |
| 2 | "1" | 1.0 |
| 1 | "2" | 1.0 |
| 2 | "1" | 1.0 |
| 2 | "2" | 2.0 |
对于第二行和第三行,我很难理解是如何得出的。例如,在 row_1 (Id = 1),@record = Num,为什么 n = 1 而不是 2?
在 row_3,@record = Num,为什么 n = 3 而不是 2?
只有一个@record 全局变量吗?还是每个 num 都有自己的 @record 变量?
谁能帮我理解@sql 变量逻辑?谢谢!
【问题讨论】:
标签: mysql mysql-variables