mysql - DATEDIFF 和自己做减法有什么区别

标签 mysql sql

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)=1w1.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/

相关文章:

android - 使用 CASE 条件函数对多列进行分组

sql - 在 Postgresql 上传递给 NOT IN 时,子查询和值之间有什么区别?

mysql - Multi-Tenancy 数据库,每个表上都有租户 ID

c# - LINQ to Entities 外键关联

mysql - 将特定记录从一个数据库导入到另一个数据库

php - 如何从 Twitter 消息 ID 'tag:search.twitter.com,2005:7550668919283712' 中删除此标签

php - 获得最高分,但删除重复用户 (SQL)

sql - DB2 AS/400 iseries 在 where 子句中使用别名

mysql - 如何将此 SQL 转储导入到 PhpMyAdmin 中而不出现此错误?

mysql - 推荐的用户信息数据库结构