如何获取特定日期的最新数据? [MYSQL]

时间:2015-08-13 06:58:00

标签: php mysql sql max distinct

如何获取MySQL中特定日期的最新数据?

我们假设我的数据库中记录了一列日期

dates      |     time     |    value
---------------------------------------------
2015-08-05 |    11:03:02  |    200       
2015-08-05 |    23:04:22  |    2400
2015-08-07 |    8:00:22   |    500
2015-08-08 |    13:00:11  |    400
2015-08-08 |    13:23:11  |    200
2015-08-09 |    17:00:23  |    2200
2015-08-09 |    17:06:00  |    1290
2015-08-09 |    19:22:00  |    900
2015-08-13 |    01:01:22  |    1010

我想获取特定日期的最新数据或交易,我想要的结果将是这样的

 dates      |     time    |     value
---------------------------------------------       
2015-08-05  |   23:04:22  |    2400
2015-08-07  |   8:00:22   |    500
2015-08-08  |   13:23:11  |    200
2015-08-09  |   19:22:00  |    900
2015-08-13  |   01:01:22  |    1010

只选择特定或不同日期的最新数据,可能的查询是什么?

4 个答案:

答案 0 :(得分:5)

你需要这样做以获得每个日期

select t1.dates,t1.time,t1.value from table as t1 inner join
(
select dates,max(time) as time from table group by dates
) as t2 on t1.dates=t2.dates and t1.time=t2.time

答案 1 :(得分:1)

使用

SELECT * FROM TABLE_NAME GROUP BY dates ORDER BY time desc LIMIT 1;

或者

SELECT * FROM TABLE_NAME GROUP BY dates HAVING time <= '23:59:59' LIMIT 1;

答案 2 :(得分:1)

试试这个:

SELECT `dates`, MAX(`time`) AS `time`, MAX(`value`) AS `value`
FROM `tbl_name`
GROUP BY `dates`
ORDER BY `dates` ASC

答案 3 :(得分:0)

尝试此查询:

SELECT * FROM `table` GROUP BY dates ORDER BY time DESC;