197-上升的温度

发布时间 2023-07-11 15:12:27作者: OnlyOnYourself-Lzw

上升的温度

原文地址:197. 上升的温度 - 力扣(LeetCode)

  • 题目如下所示

个人题解

这题稍微麻烦一些,因为需要使用到 MySQL 的日期(date)的相关函数,可以自行学习一下,以下为个人思考路程

  • -- 1、建表
    CREATE TABLE 197_weather (
    	id INT PRIMARY KEY,
    	recordDate DATE,
    	temperature INT
    );
    -- 2、分析题目:编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id,返回结果 不要求顺序
    
    -- 2.1、自连接(错误)
    SELECT w2.id Id from 197_weather w1, 197_weather w2 WHERE w1.id != w2.id AND w1.recordDate = w2.recordDate - 1 AND w1.temperature < w2.temperature;
    
    -- 2.2、子查询(错误)
    SELECT td.id Id from 197_weather td WHERE td.temperature > (SELECT yd.temperature FROM 197_weather yd WHERE yd.recordDate = td.recordDate - 1);
    
    -- 这道题的关键在于如何比较日期,找到当天的前一天。以上错误的原因在于直接使用 MySQL 的 date 类型数据直接减一(就算可以减成功,但是当日期月 1 月 1 日时,再减一就查不到 12 月 30 号的日期了)
    
    -- 学习 MySQL 的 date 函数的相关用法
    
    --  DATEDIFF 函数(比较两个 date 数据,看它们之间相差的天数)
    SELECT td.id Id from 197_weather td WHERE td.temperature > (SELECT yd.temperature FROM 197_weather yd WHERE DATEDIFF(td.recordDate, yd.recordDate) = 1);
    
    SELECT td.id Id FROM 197_weather td, 197_weather yd WHERE DATEDIFF(td.recordDate, yd.recordDate) = 1 AND td.temperature > yd.temperature;