美文网首页
[SQL] LeetCode题解 #197 上升的温度

[SQL] LeetCode题解 #197 上升的温度

作者: 半为花间酒 | 来源:发表于2020-05-08 17:28 被阅读0次

对SQL语句不熟悉欢迎查看我整理的笔记:[SQL] MySQL基础 + python交互

转载请注明:陈熹 chenx6542@foxmail.com (简书:半为花间酒)
若公众号内转载请联系公众号:早起Python

题目:

简单题 #197

SQL架构:

Create table If Not Exists Weather (Id int, RecordDate date, Temperature int);
Truncate table Weather;
insert into Weather (Id, RecordDate, Temperature) values ('1', '2015-01-01', '10');
insert into Weather (Id, RecordDate, Temperature) values ('2', '2015-01-02', '25');
insert into Weather (Id, RecordDate, Temperature) values ('3', '2015-01-03', '20');
insert into Weather (Id, RecordDate, Temperature) values ('4', '2015-01-04', '30');

题解

分析题目可得,最终就是要返回所有比昨天气温高的当天日期Id
需要不同行的多个变量比较,关于比较需要记住同一行内才能比较
因此第一步就是连表,两个表根据昨天今天的关系相连之后,比较气温即可

那么问题来了,RecordDate是日期类型,处理起来有点麻烦。从题目中看Id也是递增,似乎前后两天的Id相差1,先按这个思路写一下SQL语句

SELECT w2.Id
FROM Weather w1 
LEFT JOIN Weather w2
ON w1.Id + 1 = w2.Id 
AND w2.Temperature > w1.Temperature

能通过吗?不能
因为LeetCode刚好放出的示例有这个假象,实际上总表里面日期的顺序是无序的,导致不能简单用Id的递增做为连表依据

只能对RecordDate下手了,可以直接把上述代码的ONId换成RecordDate吗?

SELECT w2.Id
FROM Weather w1 
LEFT JOIN Weather w2
ON w1.RecordDate+ 1 = w2.RecordDate
AND w2.Temperature > w1.Temperature

代码会报错,因为日期类型不能简单加减
这里就涉及了几种日期处理可能用到的函数

第一种:DATEDIFF

SELECT w2.Id
FROM Weather w1 
LEFT JOIN Weather w2
ON DATEDIFF(a.RecordDate, b.RecordDate) = 1 
AND w2.Temperature > w1.Temperature

利用DATEDIFF可以之间判断前后两个日期的差值

这里用CROSS JOINWHERE也可以,后续不在赘述

SELECT w2.Id
FROM Weather w1 
CROSS JOIN Weather w2
ON DATEDIFF(a.RecordDate, b.RecordDate) = 1 
WHERE w2.Temperature > w1.Temperature

第二种:DATE_SUB

SELECT w2.Id
FROM Weather w1, Weather w2
WHERE w1.RecordDate = DATE_SUB(w2.RecordDate, INTERVAL 1 DAY)
AND w1.Temperature < w2.Temperature

第三种:ADDDATE

DATE_SUB相反,ADDDATE是加法

SELECT w2.Id
FROM Weather w1
JOIN Weather w2
ON w2.RecordDate = ADDDATE(w1.RecordDate, 1)
AND w2.Temperature > w1.Temperature

相关文章