leetcode问题197.Rising Temperature
给定一个天气表,编写一个 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 |
+---------+------------------+------------------+
For example, return the following Ids for the above Weather table:
+----+
| Id |
+----+
| 2 |
| 4 |
+----+
我不知道函数DATEDIFF()
,所以我写了我的sql解决方案:
select w1.Id
from Weather w1,Weather w2
where w1.RecordDate - w2.RecordDate = 1
and w1.Temperature > w2.Temperature
我完成了测试用例,但提交错误,正确的解决方案是使用函数 DATEDIFF()
select w1.Id
from Weather w1,Weather w2
where DATEDIFF(w1.RecordDate,w2.RecordDate)=1
and w1.Temperature > w2.Temperature
所以我的问题是两者之间有什么区别
DATEDIFF(w1.RecordDate,w2.RecordDate)=1
和w1.RecordDate - w2.RecordDate = 1
感谢您的帮助
最佳答案
如果 RecordDate
的数据类型是 DATETIME
而不是 DATE
,则减去它们会返回一个大值,其中也包含时间之间的差异作为日期。例如
mysql> select cast('2019-03-21 10:20:30' as datetime) - cast('2019-03-11 9:15:20' as datetime) as difference;
+-----------------+
| difference |
+-----------------+
| 10010510.000000 |
+-----------------+
但如果它们是DATE
,那么减法应该与DATEDIFF()
相同:
mysql> select cast('2019-03-21' as date) - cast('2019-03-11' as date) as difference;
+------------+
| difference |
+------------+
| 10 |
+------------+
关于mysql - DATEDIFF 和自己做减法有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55699829/