0
点赞
收藏
分享

微信扫一扫

【LeetCode题库】197. 上升的温度 —— 连接查询

文章目录

我是一名立志把细节说清楚的博主,欢迎【关注】🎉 ~

原创不易, 如果有帮助 ,记得【点赞】【收藏】 哦~ ❥(^_-)~

如有错误、疑惑,欢迎【评论】指正探讨,我会尽可能第一时间回复的,谢谢支持


原题

表: Weather

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

id 是该表具有唯一值的列。
没有具有相同 recordDate 的不同行。
该表包含特定日期的温度信息

编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 id 。

返回结果 无顺序要求 。

结果格式如下例子所示。

示例 1:

输入:
Weather 表:

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

输出:

+----+
| id |
+----+
| 2  |
| 4  |
+----+

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


题解

解法一:内连接,执行耗时740ms。

SELECT a.id FROM Weather AS a,Weather AS b
WHERE DATEDIFF(a.recordDate,b.recordDate) = 1 
	AND a.Temperature >b.Temperature;

解法二:交叉连接 / 笛卡尔积,执行耗时611ms。

SELECT a.id
FROM weather AS a 
	CROSS JOIN weather AS b 
    ON DATEDIFF(a.recordDate, b.recordDate) = 1
WHERE a.Temperature  > b.Temperature ;

解法三:内连接,执行耗时454ms。

SELECT a.id
FROM weather AS a 
	INNER JOIN weather AS b 
    ON DATEDIFF(a.recordDate, b.recordDate) = 1
WHERE a.Temperature  > b.Temperature;

解法四:执行耗时396ms。

SELECT id
FROM
    (SELECT 
        id,
        temperature,
        recordDate,
        LAG(recordDate,1) OVER(ORDER BY recordDate) AS last_date,
        LAG(temperature,1) OVER(ORDER BY recordDate) AS last_temperature
    FROM Weather) a
WHERE temperature > last_temperature AND datediff(recordDate, last_date) = 1

解题笔记

  • AS 起别名。
  • JOIN 连接查询。
    • 图文详解,情查看文章:【MySQL】连接查询(JOIN 关键字)—— 图文详解:内连接、外连接、左连接、左外连接、右连接、右外连接、全连接、全外连接
  • DATEDIFF() 日期函数。
  • LAG() 偏移分析函数。
    • LAG() OVER() 向上偏移。
    • LEAD() OVER() 向下偏移。
  • OVER() 窗口函数,窗口 可以理解为记录集合,窗口函数 就是在满足某种条件的记录集合上执行的特殊函数。
  • ORDER BY 关键字,结果排序。
    • 关键字详解,请看文章:【MySQL】查询数据,对结果进行排序(关键字:ORDER BY)

注意:在实际的工作中,要注意部分函数的使用,可能会引发索引失效,导致性能下降。


我是一名立志把细节说清楚的博主,欢迎【关注】🎉 ~

原创不易, 如果有帮助 ,记得【点赞】【收藏】 哦~ ❥(^_-)~

如有错误、疑惑 ,欢迎【评论】指正探讨,我会尽可能第一时间回复的,谢谢支持

举报

相关推荐

0 条评论