MySQL从日期列中排序每个第一个唯一行?

时间:2011-02-06 19:14:01

标签: mysql

我有一张桌子如下,我无法得到我想要的结果。

我想要的是获取每个唯一user_id的最新消息。我之前曾问过类似的问题,但我觉得自己像个白痴,因为我仍然没有得到它。我怎么想一起使用MySQL order bygroup by?使用distinct也无效。

+---------+---------------------+------------------+
| user_id | created_at          | message          |
+---------+---------------------+------------------+
|       2 | 2011-02-06 19:53:59 | sd               |
|       2 | 2011-02-06 20:11:41 | working on st..  |
|       3 | 2011-02-06 20:40:14 | testing applica..|
|       3 | 2011-02-06 21:35:11 | testing appli..  |
|       3 | 2011-02-06 23:09:34 | testing af..     |
+---------+---------------------+------------------+

这是应该返回的方式

+---------+---------------------+------------------+
| user_id | created_at          | message          |
+---------+---------------------+------------------+
|       2 | 2011-02-06 20:11:41 | working on st..  |
|       3 | 2011-02-06 23:09:34 | testing af..     |
+---------+---------------------+------------------+

这确实以正确的格式返回,但它会获取一些随机消息。

select user_id,created_at, message from status group by user_id order by created_at desc

谢谢。

2 个答案:

答案 0 :(得分:9)

SELECT
  user_id,
  created_at,
  message
FROM
  status
    JOIN
      (SELECT user_id,MAX(created_at) AS max 
       FROM status 
       GROUP BY user_id) max_created_at ON 
     (max_created_at.user_id = user_id AND max_created_at.max = created_at)

答案 1 :(得分:0)

select distinct(user_id) from status order by created_at  DESC