mysql - 如何在 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=...
解决方案
我不明白为什么我写的方式不起作用
因为您正在比较 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 将大于另一个 - 它们将相等,因为它是同一行。
推荐阅读
- tensorflow - 嵌入层输出形状为 2D
- javascript - 无法从 React 客户端向服务器发送数据
- firebase - nuxt存储模块模式下的firebase身份验证
- javascript - 使用 Javascript 创建表(tableee 添加)
- c# - 使用 c#.net 窗口窗体注册条形码扫描仪并仅从扫描仪接收数据
- sql - SQL Server 查询更新重复记录
- chef-infra - [chef]:查看节点上所有可用的数据包
- ios - UIModalTransitionStylePartialCurl 使我的应用程序崩溃
- python - cli.py __init__.py 等问题的烧瓶会话错误
- java - Spring Data JPA空指针异常