我需要进行一个 MySQL 连接,将每天的温度测量值和当天的最高温度结合起来。
- 每天都会存储新的温度测量值。
- 使用该时间段的开始日期存储每个时间段的最高温度。
我有两个表:温度(包含测量值)和最大温度(包含一段时间内的最高温度)。
table temperatures
================
id (int)
temperature (decimal)
measure_date (date)
table thresholds
================
id (int)
max_temperature (decimal)
startdate (date)
假设,我在表阈值中有两条记录:
1 | 15 | 2014-12-31
2 | 14 | 2015-01-04
有没有办法获得这样的记录集?
measure_date | temperature | max_temperature
--------------------------------------------
2015-01-01 | 12 | 15
2015-01-02 | 11 | 15
2015-01-03 | 12 | 15
2015-01-04 | 14 | 14
2015-01-05 | 16 | 14
2015-01-06 | 13 | 14
不幸的是,阈值表不保存结束日期,或者我可以进行连接,其中温度.measure_date 位于阈值.开始日期和阈值.结束日期之间。
最佳答案
由于您没有结束日期,因此您必须使用子查询找到自己的最大结束值...我是如何解决这个问题的:
select b.measure_date, b.temperature, a.max_temperature
from thresholds a
inner join temperatures b on b.measure_date >= a.startdate
where a.startdate = (select max(startdate)
from thresholds a2
where a2.startdate <= b.measure_date);
基本上我在这里所做的是:
- 连接两个表,条件是measure_date 高于或等于startdate。
- 请确保开始日期尽可能大,因为我们没有结束日期。
关于MySQL 日期之间的条件连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27994367/