如何编写MySQL Select语句以显示每个UserID的最新条目?

时间:2014-12-14 20:46:45

标签: mysql sql

我有一个允许用户输入数据的MySQL表。

该表具有UserID字段,标题,描述和timeinserted(当前时间戳)。

我试图编写一个MySQL Select语句,它将返回每个UserID的最后一行数据。

例如,如果表中有2个唯一的用户ID,则应返回两行,其中包含最新插入的时间戳。

示例表格内容

+--------+------------+------------------+---------------------+
| UserID |   Title    |   Description    |    TimeInserted     |
+--------+------------+------------------+---------------------+
|      1 | Some title | Some Description | 2014-12-12 10:00:00 |
|      2 | More title | Desc             | 2014-11-11 12:12:00 |
|      2 | Some title | Some Description | 2013-12-12 10:00:00 |
|      2 | More title | Desc             | 2014-09-10 12:12:00 |
|      1 | Some title | Some Description | 2014-12-12 10:00:00 |
|      2 | More title | Desc             | 2013-11-11 13:12:00 |
|      1 | Some title | Some Description | 2014-12-12 08:00:00 |
|      2 | More title | Desc             | 2014-08-11 11:12:00 |
+--------+------------+------------------+---------------------+

提前致谢

3 个答案:

答案 0 :(得分:2)

您可以通过

使用一个简单的组来获取最新条目
select userid, max(TimeInserted) from content group by userid

在WHERE子句中使用group by的结果,如下所示:

select * 
   from content 
where (userid, TimeInserted) in

(
  select userid, max(TimeInserted) from content group by userid  
)

答案 1 :(得分:0)

有很多方法可以做到这一点,其中一种方法是使用left join

select t1.* from `Field` t1
left join `Field` t2 on t1.UserID = t2.UserID
and t1.TimeInserted < t2.TimeInserted
where t2.UserID is null

查看此处的文档http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html

答案 2 :(得分:0)

这对我有用,虽然比我希望的时间长一点。

SELECT DISTINCT t1.userid, 
                t1.title, 
                t1.description, 
                t1.timeinserted 
FROM   posts t1 
       JOIN (SELECT userid             AS id, 
                    Max(timeinserted)  AS max_time 
             FROM   posts 
             GROUP  BY id) t2 
         ON t1.userid = t2.id 
            AND t1.timeinserted = t2.max_time;