前提条件:
表: Weather
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id 是该表具有唯一值的列。
没有具有相同 recordDate 的不同行。
该表包含特定日期的温度信息
编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 id
。返回结果 无顺序要求 。结果格式如下例子所示。
CREATE TABLE Weather (
id INT,
recordDate DATE,
temperature INT
);
INSERT INTO
Weather
VALUES
(1, '2015-01-01', 10),
(2, '2015-01-02', 25),
(3, '2015-01-03', 20),
(4, '2015-01-04', 30);
思路:
- 先笛卡尔积
- 过滤找出日期前后日期相差一天
- 查询
优化:
- 使用连接替代交叉连接
SELECT
w2.id id
FROM
weather w1
JOIN
Weather w2 ON w2.recordDate=DATE_ADD(w1.recordDate,INTERVAL 1 DAY ) AND w1.temperature < w2.temperature;
实现:
-
SELECT * FROM weather w1 CROSS JOIN weather w2;
2.
SELECT
*
FROM
weather w1 CROSS JOIN weather w2
WHERE
DATEDIFF(w2.recordDate,w1.recordDate)=1 ;
3.
SELECT
w2.id id
FROM
weather w1 CROSS JOIN weather w2
WHERE
DATEDIFF(w2.recordDate,w1.recordDate)=1 and w1.temperature<w2.temperature;
标签:01,197,id,weather,w2,w1,recordDate,leetcode,温度 From: https://www.cnblogs.com/kezz/p/18498922