Buckle 180. consecutive numbers

Buckle 180. consecutive numbers

https://leetcode-cn.com/problems/consecutive-numbers/

Write a SQL query to find all numbers that appear at least three times in a row.

+ ---- + ----- +
| 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 at least three consecutive times.

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

 

Points to note:

1. The keyword DISTINCT is to prevent the return of duplicate elements (a number appears more than 3 times in a row)

2. Three-meter connection

3. Conditional query, conditions appearing three times in a row

# Write your MySQL query statement below
select 
distinct i1.num as ConsecutiveNums#关键字 DISTINCT是防止返回重复元素(一个数字连续出现超过 3 次)
from logs i1,logs i2,logs i3#三表连接
where i1.id=i2.id-1 #条件查询,连续出现三次的条件
    and i2.id=i3.id-1
    and i1.num=i2.num 
    and i2.num=i3.num;

 

Published 23 original articles · praised 0 · visits 137

Guess you like

Origin blog.csdn.net/qq_35683407/article/details/105424856