题目:编写一个 SQL 查询,查找所有至少连续出现三次的数字。
±—±----+
Id | Num |
---|---|
1 | 1 |
2 | 1 |
3 | 1 |
4 | 2 |
5 | 1 |
6 | 2 |
7 | 2 |
例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。
ConsecutiveNums |
---|
1 |
分析:
- 先分析题目,关键字:连续 数字 列名为:consecutivenums
- 思考判断逻辑:对于连续的三个数字,我们可以用a,b,c分别表示(这三个数之间的对比用自连接实现),有以下的充要条件要符合
a.id=b.id-1
b.id=c.id-1
a.num=b.num
b.num=c.num
3.获得答案
答案:
select distinct l1.num as consecutivenums
from logs l1,logs l2,logs l3
where l1.id=l2.id-1
and l2.id=l3.id-1
and l1.num=l2.num
and l2.num=l3.num;
以上是官方的解答,但是事实上,这个解法复用性不高,如果在中间有一些id不连续的话,就不适合了
在评论区里面我发现了一个大佬的解答方法(370ms)
select
distinct Num as ConsecutiveNums
from
(select Num,
if(@pre=Num,@count := @count+1,@count := 1) as nums,
@pre:=Num
from Logs as l ,
(select @pre:= null,@count:=1) as pc
) as n
where nums >=3;
这里用了if函数,:=符号以及@
关于:=和=的用法,我们可以去
:=和=的区别
这里的if函数的运用
mysql中if()函数的用法
这个适用于id不连续时的统计,复用性更高。