给定一个 Weather 表,编写一个 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 | +————-+—————————+—————————+例如,根据上述给定的 Weather 表格,返回如下 Id: +——+ | Id | +——+ | 2 | | 4 | +——解决思路。查询两次Weather 只要w1.日期 减去一 等于 昨天的日期w2. RecordDate 并且w1.温度> w2.温度就可以了。但是这种速度非常慢
我的SQL:

  1. SELECT
  2. w2.Id
  3. FROM
  4. Weather w1,
  5. Weather w2
  6. WHERE
  7. w1.RecordDate = DATE_SUB(w2.RecordDate, INTERVAL 1 DAY)
  8. AND w2.Temperature > w1.Temperature

其他SQL:将日期转成天数进行操作,发现简单了许多

示例一:
select wt1.Id
from Weather wt1,Weather wt2
where wt1.Temperature > wt2.Temperature AND TO_DAYS(wt1.RecordDate)-TO_DAYS(wt2.RecordDate)=1;
示例二:
SELECT
    weather.id AS 'Id'
FROM
    weather
        JOIN
    weather w ON DATEDIFF(weather.RecordDate, w.RecordDate) = 1
        AND weather.Temperature > w.Temperature;

TO_DAYS(date):给定一个日期,返回一个天数(年为0以来的天数)。或者使用DATEDIFF

DATEDIFF() 函数返回两个日期之间的天数。