如何根据mysql中的日期时间字段获取最新数据?

时间:2015-11-18 04:29:58

标签: mysql

我正在尝试获取sql中每个日期时间字段的最新数据。任何人都可以帮我解决这个问题.. 这是我的表结构。

| ID | USER   |       TIME          |
-------------------------------------
|  2 |    abc | 2009-01-01 01:00:00 |
|  3 |    abc | 2009-01-01 22:00:00 | 
|  5 |    abc | 2009-01-01 10:00:00 | 
|  6 |    xyz | 2009-01-02 01:00:00 |
|  7 |    xyz | 2009-01-02 22:00:00 | 
|  8 |    xyz | 2009-01-02 10:00:00 |

我希望输出像这样。

| ID | USER   |       TIME          |
-------------------------------------
|  3 |    abc | 2009-01-01 22:00:00 | 
|  7 |    xyz | 2009-01-02 22:00:00 | 

编辑:需求变更。正如我所说,我希望每个用户都能获得每个日期的最新记录。

| ID | USER   |       TIME          |
-------------------------------------
|  2 |    abc | 2009-01-01 01:00:00 |
|  3 |    abc | 2009-01-01 22:00:00 | 
|  5 |    abc | 2009-01-01 10:00:00 | 
|  6 |    xyz | 2009-01-01 01:00:00 |
|  7 |    xyz | 2009-01-01 22:00:00 | 
|  8 |    xyz | 2009-01-01 10:00:00 |
| 10 |    abc | 2009-01-04 09:00:00 |
| 11 |    abc | 2009-01-04 02:00:00 |
| 15 |    xyz | 2009-01-04 04:00:00 |
| 25 |    xyz | 2009-01-04 06:00:00 |

我希望输出像这样。

| ID | USER   |       TIME          |
-------------------------------------
|  3 |    abc | 2009-01-01 22:00:00 | 
|  7 |    xyz | 2009-01-01 22:00:00 | 
| 10 |    abc | 2009-01-04 09:00:00 |
| 25 |    xyz | 2009-01-04 06:00:00 |

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT * FROM test GROUP BY name ORDER BY name asc, time DESC LIMIT 2

SQL Fiddle

答案 1 :(得分:-1)

试试这个:

  

SELECT ID,USER,TIME FROM tbl_name Group By User Order By TIME DESC,USER ASC;