I am looking into the following 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
Where Logs table is like:
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
And the outputs of the query is like:
|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 |
For the second and third row, I have hard time understand how is derived. For example, in row_1 (Id = 1), @record = Num, why n = 1 not 2?
In row_3, @record = Num, why n = 3 not 2?
Is there only one @record global variable? or each num has its own @record variable?
Could anyone please help me to understand the @sql variable logic? Thanks!