題意:求表中連續出現3次以上的數據. 因此,根據題意構造第一版本答案(使用連續的ID進行比較): 當前版本答案通過了測試,但是運行效率太低了. 分析原因,可能與 條件相關,當 為0時, 1不會尋找到相關數據,導致 執行緩慢. 因此,修改為如下所示: 此版本,效率得到了巨大的提高。 ...
Write a SQL query to find all numbers that appear at least three times consecutively.
+----+-----+
| 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 consecutively for at least three times.
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+
題意:求表中連續出現3次以上的數據.
因此,根據題意構造第一版本答案(使用連續的ID進行比較):
# Write your MySQL query statement below
SELECT DISTINCT t1.Num AS ConsecutiveNums
FROM
Logs t1,
Logs t2,
Logs t3
WHERE
t1.Id = t3.Id - 1
AND t2.Id = t3.Id + 1
AND t1.Num = t2.Num
AND t2.Num = t3.Num;
當前版本答案通過了測試,但是運行效率太低了.
分析原因,可能與t1.Id = t3.Id - 1
條件相關,當t3.Id
為0時,-1不會尋找到相關數據,導致sql
執行緩慢.
因此,修改為如下所示:
# Write your MySQL query statement below
# Write your MySQL query statement below
SELECT DISTINCT t1.Num AS ConsecutiveNums
FROM
Logs t1,
Logs t2,
Logs t3
WHERE
t2.Id = t1.Id + 1
AND t3.Id = t1.Id + 2
AND t1.Num = t2.Num
AND t2.Num = t3.Num;
此版本,效率得到了巨大的提高。