第十一周_A-leetCode-SQL-连续出现的数字

70 阅读1分钟

今天开始 SQL 练习


/**
* https://leetcode.cn/problems/consecutive-numbers/description/
* 示例 1:
*
* 输入:
* Logs 表:
* +----+-----+
* | Id | Num |
* +----+-----+
* | 1  | 1   |
* | 2  | 1   |
* | 3  | 1   |
* | 4  | 2   |
* | 5  | 1   |
* | 6  | 2   |
* | 7  | 2   |
* +----+-----+
* 输出:
* Result 表:
* +-----------------+
* | ConsecutiveNums |
* +-----------------+
* | 1               |
* +-----------------+
* 解释:1 是唯一连续出现至少三次的数字。
*/
public class 连续出现的数字 {

    /**
* 使用自连接 检索到哪个Num连续出现三次即可
*/

    public static void main(String[] args) {
        String s="select * from " +
            "Logs log1," +
            "Logs log2," +
            "Logs log3 " +
            "where " +
            "log1.id = log2.id-1 and" +
            "log2.id = log3.id-1 and" +
            "log1.num = log2.num and" +
            "log2.num = log3.num ";
    }
}

出于题解,肯定不能使用 select * ;换成题解的要求:select log1.num ConsecutiveNums from xxx

但是如果连续四个数都相同,那么久会查出来两个。所以把结果集再 distinct 一下即可

至于解答区还有窗口函数的,我觉得他们挺厉害的。但是也很复杂,有点看不下去。如果实际开发中,我一定不会使用窗口函数,因为就算我自己明白了,对于其他人也是个不小的‘负担’。