mysql - 如何获取特定日期范围的最新数据?
问题描述
我有通过以下查询获得的示例产品表
select * from table where timestamp BETWEEN '2018-01-10 00:00:00' AND '2018-01-11 23:59:59
id timestamp product
1 10-1-2018:10:02:02 a
2 10-1-2018:10:02:03 b
3 11-1-2018:10:02:05 a
4 11-1-2018:10:02:09 b
5 11-1-2018:10:02:19 a
6 11-1-2018:10:02:23 b
所需输出
id timestamp product
1 10-1-2018:10:02:02 a
2 10-1-2018:10:02:03 b
5 11-1-2018:10:02:19 a
6 11-1-2018:10:02:23 b
我尝试了以下查询
第一个查询给我 1,2,3,4 作为结果
select * from (select * from table where timestamp BETWEEN '2018-01-10 00:00:00' AND '2018-01-11 23:59:59') AS q group by Date(timestamp), product
select id, max(timestamp), product from (select * from table where timestamp BETWEEN '2018-01-10 00:00:00' AND '2018-01-11 23:59:59') AS q group by Date(timestamp), product
我的问题是如果我有此类数据,如何获取特定日期范围的最新数据?
解决方案
考虑以下:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,timestamp DATETIME NOT NULL
,product CHAR(1) NOT NULL
);
INSERT INTO my_table VALUES
(1,'2018-01-10:10:02:02','a'),
(2,'2018-01-10:10:02:03','b'),
(3,'2018-01-11:10:02:05','a'),
(4,'2018-01-11:10:02:09','b'),
(5,'2018-01-11:10:02:19','a'),
(6,'2018-01-11:10:02:23','b');
SELECT a.*
FROM my_table a
JOIN
( SELECT product
, MAX(timestamp) timestamp
FROM my_table
GROUP
BY product
, DATE(timestamp)
) b
ON b.product = a.product
AND b.timestamp = a.timestamp;
+----+---------------------+---------+
| id | timestamp | product |
+----+---------------------+---------+
| 1 | 2018-01-10 10:02:02 | a |
| 2 | 2018-01-10 10:02:03 | b |
| 5 | 2018-01-11 10:02:19 | a |
| 6 | 2018-01-11 10:02:23 | b |
+----+---------------------+---------+
顺便说一句,这是 SO 上此标签下最常见的一个问题。
推荐阅读
- svg - 如何从带有材质 ui 的 SVG 图像创建 SVG 图标?
- javascript - 如何使用javascript打开剑道角度日期选择器弹出窗口
- php - 使用自动生成的 DATETIME 和默认值 CURRENT_TIMESTAMP 插入新对象的 symfony 4 教义错误
- python - 解析电子邮件以识别关键字
- javascript - Django中可修改的项目符号列表
- python - 如何使用 Python 在浏览器中打开网站?
- c# - 使用 LINQ、GroupBy 更改输出样式
- extjs - Sencha ExtJs5 一个模型和一个视图中的多个模型
- c++ - MPI_DOUBLE_INT 和 C++ 结构
- sql - Pivot 为 Pivot Key 的 Null 值创建一个额外的行