首页 > 解决方案 > 如何在 SQL 中选择一个连续的日期

问题描述

这是我要使用的数据

create table weather(
    id int,
    recorddate date,
    temp int,
    primary key (id)
);

insert into weather values (1, '2015-01-01', 10);
insert into weather values (2, '2015-01-02', 15);
insert into weather values (3, '2015-01-03', 20);

我想选择一个温度比前一天高的日期,我使用了这个查询:

select id
from weather a
where id = (select id from weather b where datediff(a.recorddate, b.recorddate) = -1 and b.temp > a.temp)

查询返回 0 记录,我知道子查询的逻辑是正确的,但由于某种原因它不起作用。

更新

我不是在寻找编写此查询的替代方法,我想知道上面的查询有什么问题?

更新

我弄错的部分是我想通过写来为 id赋值where id=...

标签: mysqlsql

解决方案


我不明白为什么我写的方式不起作用

因为您正在比较 a.id = b.id,但您的条件保证它们永远不会相等。

这是一个演示,显示您可能打算匹配的行,因为它们具有 datediff = -1 和 b.temp > a.temp,但在这两种情况下,id 是不同的。

mysql> select a.id as a_id, b.id as b_id, 
  datediff(a.recorddate, b.recorddate) as datediff, 
  b.temp > a.temp, a.id = b.id 
from weather a cross join weather b;
+------+------+----------+-----------------+-------------+
| a_id | b_id | datediff | b.temp > a.temp | a.id = b.id |
+------+------+----------+-----------------+-------------+
|    1 |    1 |        0 |               0 |           1 |
|    2 |    1 |        1 |               0 |           0 |
|    3 |    1 |        2 |               0 |           0 |
|    1 |    2 |       -1 |               1 |           0 | <--
|    2 |    2 |        0 |               0 |           1 |
|    3 |    2 |        1 |               0 |           0 |
|    1 |    3 |       -2 |               1 |           0 |
|    2 |    3 |       -1 |               1 |           0 | <--
|    3 |    3 |        0 |               0 |           1 |
+------+------+----------+-----------------+-------------+

a.id = b.id 的唯一方法是如果您要比较完全相同的行(id 是主键,因此只有一行可以具有该值),但在这些情况下,datediff 自然会为 0 并且两者都不是temp 将大于另一个 - 它们将相等,因为它是同一行。


推荐阅读