leetcode-180. 连续出现的数字

  • 题目

SQL架构

Create table If Not Exists Logs (Id int, Num int)
Truncate table Logs
insert into Logs (Id, Num) values ('1', '1')
insert into Logs (Id, Num) values ('2', '1')
insert into Logs (Id, Num) values ('3', '1')
insert into Logs (Id, Num) values ('4', '2')
insert into Logs (Id, Num) values ('5', '1')
insert into Logs (Id, Num) values ('6', '2')
insert into Logs (Id, Num) values ('7', '2')

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

±—±----+
| Id | Num |
±—±----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
±—±----+
例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

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

来源:力扣(LeetCode)
链接:180. 连续出现的数字
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 分析

要查找所有至少连续出现三次的数字,直接同时查找三张表,然后比较他们的值和顺序即可。
观察原表很容易发现,其Id就是顺序,所以判断顺序时用Id即可。
另外需注意要使用表的别名,用distinct消去重复值。

  • 代码
# Write your MySQL query statement below
select distinct l1.Num as ConsecutiveNums from Logs l1,Logs l2,Logs l3 where
l1.Num=l2.Num and l2.Num=l3.Num and l1.Id=l2.Id-1 and l2.Id =l3.Id-1;

在这里插入图片描述

2019.12.15

发布了52 篇原创文章 · 获赞 59 · 访问量 6831

猜你喜欢

转载自blog.csdn.net/ataraxy_/article/details/103548623