这是我要处理的数据
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 条记录,我知道子查询的逻辑是正确的,但由于某些原因它不起作用。
更新
我不是在寻找编写此查询的替代方法,我想知道上面的查询有什么问题?
更新
我弄错的部分是我想通过编写 where id=...
assign 一个值给 id/p>
最佳答案
I don't understand why the way I wrote it does not work
因为您正在比较 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 并且两个温度都不会大于另一个 — 它们将相等,因为它在同一行。
关于mysql - 如何在SQL中选择一个连续的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55242165/