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