LeetCode MySQL日期比较函数

LeetCode题目

链接:https://leetcode-cn.com/problems/rising-temperature

表 Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+

id 是这个表的主键
该表包含特定日期的温度信息

编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id 。

返回结果 不要求顺序 。

查询结果格式如下例:

Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+

Result table:
+----+
| id |
+----+
| 2  |
| 4  |
+----+

2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

解答

该题要求比较日期数据的差值。
1, 思路一: 错误思路, 直接对日期加一。 日期的月份和日是循环变化的,单纯的加一无法做到循环。

    SELECT DISTINCT a.id
    FROM Weather a, Weather b
    WHERE a.recordDate = b.recordDate+1 
	  AND a.Temperature > b.Temperature;
  1. 思路二:DATEDIFF(a, b)日期函数,该函数返回a-b的天数差值。
   SELECT  a.id
   FROM Weather a join Weather b
   ON DATEDIFF(a.recordDate, b.recordDate) = 1
      AND a.temperature > b.temperature;
  1. 思路三: DATE_ADD()函数,对b日期加一天后再与a日期比较是否相等。优点是符合MySQL高效查询的原则(令等式左边不出现算式,更好的利用索引)。
   A.recordDate = DATE_ADD(B.recordDate, INTERVAL 1 DAY)
posted @ 2021-01-22 09:30  Daybreaking  阅读(148)  评论(0)    收藏  举报