2011-02-06 64 views
0

我有一个表,如下,我无法得到我想要的结果。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 

谢谢。

回答

8
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) 
0
select distinct(user_id) from status order by created_at DESC 
+0

`message`是很重要的,不要以为不同的作品有多个领域。 – saint 2011-02-06 19:26:01

+0

select distinct(user_id),message ... – iBiryukov 2011-02-06 19:26:50

相关问题