leetcode力扣数据库SQL题目及解答(五)

180. 连续出现的数字(中等)

编写一个 SQL 查询,查找所有至少连续出现三次的数字。
题解:

思路1:自连接

这种方法的特点是,查找连续出现N次,就需要表自连接N次。连接次数少还行,如果连接次数多了,查询效率肯定就很慢。

-- 方法1:
select distinct(l1.Num) as ConsecutiveNums
from Logs as l1
join Logs as l2 on l1.Id = l2.Id-1 and l1.Num = l2.Num
join Logs as l3 on l2.Id = l3.Id-1 and l2.Num = l3.Num

----------------------------------------------------
-- 方法2:
select a.Num as ConsecutiveNums
from Logs a
left join Logs b on b.id = a.Id + 1 
left join Logs c on c.id = a.Id + 2 
where a.Num = b.Num and a.Num = c.Num
group by a.Num

思路2:自连接+限定序号

这个思路是谈论区的盆友分享的,我觉得很有代表性,刚好解决了连接次数过多导致查询变慢的问题。

这个方法是将表自连接两次,在b表里面限定序号Id的范围(如果是连续出现N次,则限定的序号范围为0 ~ N-1)

select distinct a.Num as ConsecutiveNums
from Logs a join Logs b 
on b.Id - a.Id <=2 and a.Num = b.Num and b.Id - a.Id >= 0
group by a.Id
having count(b.Num)  >= 3

你可能感兴趣的:(SQL,数据库,mysql,sql)