Consecutive Numbers leetcode

Consecutive Numbers
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  |
+----+-----+
For example, given the above Logs table, 1 is the only number that appears consecutively
 for at least three times.

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


solution:
用普通的关联
select distinct a.Num as ConsecutiveNums from Logs a,logs b,Logs c
where a.Num = b.Num and b.Num = c.Num
and a.Id = b.Id-1 and b.Id = c.Id-1

与上面相似的 咱们换成 Join 关联
select distinct a.Num as ConsecutiveNums from Logs a
join logs b
Join Logs c
where a.Num = b.Num and b.Num = c.Num
and a.Id = b.Id-1 and b.Id = c.Id-1

固然 这边的条件 写在 on关联仍是 放在where中 结果是同样
实际执行计划 不知道有什么变化
SELECT DISTINCT l1.Num FROM Logs a
JOIN Logs b ON a.Id = b.Id - 1
JOIN Logs  c ON a.Id = c.Id - 2
WHERE a.Num = b.Num AND b.Num = c.Num;

而后又是设置两个变量的写法
SELECT DISTINCT Num as ConsecutiveNums FROM (
SELECT Num, @count := IF(@pre = Num, @count + 1, 1) AS n, @pre := Num
FROM Logs, (SELECT @count := 0, @pre := -1) AS init
) AS t WHERE t.n >= 3;

https://github.com/woshiyexinjie/leetcode-xingit

相关文章
相关标签/搜索