• LeetCode——Consecutive Numbers


    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;
    

    此版本,效率得到了巨大的提高。

    PS:
    如果您觉得我的文章对您有帮助,请关注我的微信公众号,谢谢!
    程序员打怪之路

  • 相关阅读:
    redis的rpm包下载安装
    linux下创建普通用户并赋予某个目录的读写权限
    nginx软件优化
    GIT分支简单操作
    mysqldump导入导出数据
    rsync守护进程方式同步实例-004
    rsync多模块配置&排除功能-003
    rsync数据同步方式-002
    rsync简单介绍-001
    Redis cluster 日常操作命令
  • 原文地址:https://www.cnblogs.com/jason1990/p/11641911.html
Copyright © 2020-2023  润新知