mysql - 如何在某个日期之后选择 MAX(date)
问题描述
背景:
我正在编写一个 Python 脚本来获取一些数据。我有 2 个表engine_hours
和machines
一个 SQL 数据库。我想获取前 2 天收到的最新收到的数据(通过 this 完成date_recorded >=
)。
表格:
第一张表:
engine_hours
=============
machine_id
date_recorded
value
第二张表:
machines
========
id
title
样本数据表:
第一张表:
engine_hours
==================================================
machine_id | date_recorded | value
-------------+--------------------------+---------
1 | 16/10/2018 20:30:02 | 10
3 | 16/10/2018 19:02:32 | 42
2 | 16/10/2018 20:32:56 | 13
2 | 16/10/2018 19:23:23 | 12
1 | 16/10/2018 16:54:59 | 10
1 | 16/10/2018 16:52:59 | 10
1 | 14/10/2018 10:24:59 | 10
第二张表:
machines
==================
id | title
------+-----------
1 | ABC-123
2 | DEF-456
3 | GHI-789
期望的输出:
=============================================================
machine_id | title | date_recorded | value
1 | ABC-123 | 16/10/2018 20:30:02 | 10
2 | DEF-456 | 16/10/2018 20:32:56 | 13
3 | GHI-789 | 16/10/2018 19:02:32 | 42
我试过的:
我尝试了 4 种不同的查询,但都失败了:
engine_hours_query = "SELECT ma.`title`, eh.`machine_id`, eh.`value`, eh.`date_recorded` " \
"FROM `engine_hours` AS eh inner join `machines` AS ma " \
"WHERE eh.`machine_id` IN ({}) AND eh.`date_recorded` >= \"{}\" " \
" AND eh.`machine_id` = ma.`id`".format(", ".join([str(m_id) for m_id in list_of_machine_ids]),
cut_off_date)
engine_hours_query_2 = "SELECT `machine_id`, `value`, `date_recorded` FROM `engine_hours` AS eh " \
"WHERE `date_recorded` = ( SELECT MAX(`date_recorded`) " \
"FROM `engine_hours` AS eh2 " \
"WHERE eh.`machine_id` = eh2.`machine_id`)"
engine_hours_query_3 = "SELECT `machine_id`, `value`, `date_recorded` FROM `engine_hours` AS eh " \
"WHERE `date_recorded` = ( SELECT MAX(`date_recorded`) " \
"FROM `engine_hours` AS eh2 ) " \
"WHERE eh.`date_recorded` >= \"{}\"".format(cut_off_date)
engine_hours_query_4 = "SELECT ma.`title`, eh.`machine_id`, eh.`value`, eh.`date_recorded` " \
"FROM `engine_hours` AS eh inner join `machines` AS ma " \
"WHERE eh.`machine_id` IN ({}) AND eh.`date_recorded` >= \"{}\" " \
" AND eh.`machine_id` = ma.`id`".format(", ".join([str(m_id) for m_id in list_of_machine_ids]),
cut_off_date)
研究:
解决方案
这个版本应该做你想做的事:
SELECT eh.machine_id, eh.value, eh.date_recorded
FROM engine_hours eh
WHERE eh.date_recorded = (SELECT MAX(eh2.date_recorded)
FROM engine_hours eh2
WHERE eh.machine_id = eh2.machine_id
);
AND eh.date_recorded >= NOW() - INTERVAL 2 DAY
如果仍然需要该条件,您可能需要添加。
推荐阅读
- css - Angular 12 Material自定义颜色默认对比度不起作用
- xamarin.forms - Xamarin.Forms:如何请求 ACCESS_BACKGROUND_LOCATION?
- python - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'content/movies_fights/'
- javascript - 我似乎无法访问地理位置返回值
- amazon-web-services - Amazon CloudWatch 指标数学 - 滚动平均值
- excel - 执行“结束于”后单元格值消失
- pyspark - pyspark 数据框中的文件问题
- shell - 在jenkins文件中循环Hashmap并将密钥传递给shell或powershell或bat,不起作用
- python - 检查一列是否包含熊猫数据框中包含浮点值的对象
- wordpress - 寻找一种为 Wordpress 帖子创建单个图像滑块的方法