按最新时间戳选择

时间:2015-09-08 11:53:45

标签: php mysql

我有一张桌子:

+-------+--------+---------------------+
| score |  user  |      scrap_time     |
+-------+--------+---------------------+
|  200  |  Bob   | 2015-09-08 11:46:17 |
+-------+--------+---------------------+
|  210  |  Alice | 2015-09-08 11:46:17 |
+-------+--------+---------------------+
|  240  |  Bob   | 2015-09-08 11:48:00 |
+-------+--------+---------------------+
|  260  |  Alice | 2015-09-08 11:48:01 |
+-------+--------+---------------------+

我希望得到每个用户的所有得分 latest scrap_time并忽略旧版本。

示例:

+-------+--------+---------------------+
| score |  user  |      scrap_time     |
+-------+--------+---------------------+
|  240  |  Bob   | 2015-09-08 11:48:00 |
+-------+--------+---------------------+
|  260  |  Alice | 2015-09-08 11:48:01 |
+-------+--------+---------------------+


我一直试图提出一个查询,就像这样:

select * from scores where date(scrap_time) = ( select max(scrap_time) from scores);

但这并没有给我我需要的结果。

3 个答案:

答案 0 :(得分:2)

您需要获得userSELECT s.score, s.user, s.scrap_time FROM scores AS s INNER JOIN (SELECT user, max(scrap_time) AS maxTime FROM scores GROUP BY user) AS t ON s.user = t.user AND s.scrap_time = maxTime ,然后只需加入您的表格即可获得所需的结果集。以下内容应该有效:

    private var myDict: NSMutableDictionary!

Demo here

答案 1 :(得分:2)

首先,您需要找到每个用户的MAX(scrap_time),然后找到那些行

SELECT * FROM scores WHERE (user,scrap_time) IN (
 SELECT user,MAX(scrap_time) scrap_time FROM scores
 GROUP BY user);

答案 2 :(得分:0)

使用群组的最大功能,通过群组提供每个分数的最近时间

 select   score, user, max(scrap_time) 
 from     scores  
 group by score;