LeetCode数据库题目
题目
给定一个 Weather
表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。
+---------+------------------+------------------+
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
+---------+------------------+------------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+---------+------------------+------------------+
例如,根据上述给定的 Weather
表格,返回如下 Id:
+----+
| Id |
+----+
| 2 |
| 4 |
+----+
思路
- 查询目标:Id属性
- 查询范围:Weather表
- 查询条件:(1)昨天的日期 (2)温度更高
显然,这两个条件为and
关系;
对于条件(2),只需要对INT
类型的数据直接进行比较w1.Temperature > w2.Temperature
;
对于条件(1),需要对DATE
类型的数据进行比较操作,方法较多,例如:
a)使用MySQL的DataDiff
函数计算两个日期的差值:datediff(w1.RecordDate,w2.RecordDate) = 1
b)使用MySQL的TO_DAYS
函数,用来将日期换算成天数,再进行减法比较:to_days(w1.RecordDate) - to_days(w2.RecordDate) = 1
c)使用MySQL的SUBDATE
函数,实现日期减一:subdate(w1.RecordDate,1) = w2.RecordDate
解答
方法一:
select
w1.Id
from
Weather w1 join Weather w2
where
(datediff(w1.RecordDate,w2.RecordDate) = 1) AND (w1.Temperature > w2.Temperature)
方法二:
select
w1.Id
from
Weather w1 join Weather w2
where
(to_days(w1.RecordDate) - to_days(w2.RecordDate) = 1) AND (w1.Temperature > w2.Temperature)
方法三:
select
w1.Id
from
Weather w1 join Weather w2
where
(subdate(w1.RecordDate,1) = w2.RecordDate) AND (w1.Temperature > w2.Temperature)