MySQL连续数字问题:计数查询的顺序有关系吗?

时间:2018-04-08 21:22:12

标签: mysql rank

我在解决这个问题时遇到了一个难题:

Write a SQL query to find all numbers that appear at least three times consecutively.

+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |

例如,给定上面的Logs表,1是连续出现至少三次的唯一数字。

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

我的第一个解决方案:

SELECT DISTINCT Num As ConsecutiveNums
FROM (
    SELECT 
    ID, 
    Num,
    @PreNum:=Num as PreNum,
    @Count:=IF(@PreNum=Num, @Count+1,1) AS Count

    FROM Logs,
    (SELECT @PreNum:=0,@Count:=1) x

    ) y
where y.Count>=3;

上面的代码将返回不正确的结果:

{"headers":["ConsecutiveNums"],"values":[[1],[2]]}

但是,如果我移动线" @Count:= IF(@ PreNum = Num,@ Count + 1,1)AS Count,"以上" @PreNum:= Num作为PreNum",它将产生预期的结果。为什么这两行的顺序很重要?谢谢!

SELECT DISTINCT Num As ConsecutiveNums
FROM (
    SELECT 
    ID, 
    Num,
    @Count:=IF(@PreNum=Num, @Count+1,1) AS Count,
    @PreNum:=Num as PreNum


    FROM Logs,
    (SELECT @PreNum:=0,@Count:=1) x

    ) y
where y.Count>=3;

结果:

{"headers":["ConsecutiveNums"],"values":[[1]]}

1 个答案:

答案 0 :(得分:0)

我现在明白了:

@Count:=IF(@PreNum=Num, @Count+1,1) AS Count,
@PreNum:=Num as PreNum

如果我们将@Count留在" @PreNum:= Num作为PreNum" ,这意味着If逻辑仍在检查未在" @PreNum:= Num作为PreNum"重新分配的@PreNum。