techiall / Blog

🍋 [My Blog] See discussions
https://github.com/techiall/Blog/discussions
MIT License
8 stars 1 forks source link

Leetcode | 连续出现的数字 #11

Open techiall opened 6 years ago

techiall commented 6 years ago

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

+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
+----+-----+

例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

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

使用自连接,利用别名,将同一张表使用三次

连续至少出现三次,那也是就 id 号得相差 1,并且 num 的值得相等。

再利用 distinct 去重即可。

mysql

select distinct a.Num ConsecutiveNums from

Logs a 

inner join Logs b on a.id = b.id - 1

inner join Logs c on b.id = c.id - 1

where a.Num  = b.Num and b.Num  = c.Num;
jiahe224 commented 4 years ago

为何最后的条件写 a.Num = b.Num = c.Num 会不对?