给定一个 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 |
±—+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rising-temperature
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
SELECT a.Id
FROM Weather AS a cross join Weather AS b
WHERE DATEDIFF(a.RecordDate, b.RecordDate) = 1
AND a.Temperature > b.Temperature
其实
SELECT a.Id
FROM Weather AS a join Weather AS b
WHERE DATEDIFF(a.RecordDate, b.RecordDate) = 1
AND a.Temperature > b.Temperature
或者
SELECT a.Id
FROM Weather AS a , Weather AS b
WHERE DATEDIFF(a.RecordDate, b.RecordDate) = 1
AND a.Temperature > b.Temperature
都是可以的,
这个题的重点不是我搞两个表链接,而是,找到日期差一的这个方法
DATEDIFF(d1,d2) 计算日期 d1->d2 之间相隔的天数
但是还有没有其他办法来解决这个问题
使用ADDDATE函数
SELECT a.Id
FROM Weather AS a , Weather AS b
WHERE a.RecordDate=ADDDATE(b.RecordDate,1)
AND a.Temperature > b.Temperature
还可以使用DATE_SUB函数
SELECT a.Id
FROM Weather AS a , Weather AS b
WHERE DATE_SUB(a.RecordDate,INTERVAL 1 DAY)=b.RecordDate
AND a.Temperature > b.Temperature