Consecutive NumbersWrite 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 cwhere a.Num = b.Num and b.Num = c.Numand a.Id = b.Id-1 and b.Id = c.Id-1与上面类似的 我们换成 Join 关联select distinct a.Num as ConsecutiveNums from Logs ajoin logs bJoin Logs cwhere a.Num = b.Num and b.Num = c.Numand a.Id = b.Id-1 and b.Id = c.Id-1当然 这边的条件 写在 on关联还是 放在where中 结果是一样实际执行计划 不知道有什么变化SELECT DISTINCT l1.Num FROM Logs aJOIN Logs b ON a.Id = b.Id - 1JOIN Logs c ON a.Id = c.Id - 2WHERE 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 := NumFROM Logs, (SELECT @count := 0, @pre := -1) AS init) AS t WHERE t.n >= 3;